So my title was meant to be array not loop
I need to create an application that will generate random spots so far my work is this
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
public class Shape{
private int x;
private int y;
private int width;
private int height;
private Color color;
// random values with particular limits
public int randomRange(int low, int high){
Random generator = new Random();
return generator.nextInt(high - low +1) + low;
}
public Shape(int width, int height, int x, int y, Color color){
Random r = new Random();
this.width = r.nextInt(30) + 10;
this.height = this.width;
this.x = r.nextInt(400 - this.width) + 0;
this.y = r.nextInt(400 - this.height) + 0;
this.color = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
}
public void display(Graphics page) {
page.setColor(color);
page.drawOval(x, y, width, height);
page.fillOval(x, y, width, height);
}
}
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
public class ShapePanel extends JPanel{
private Shape [] drawObjects = new Shape[20];
private JButton addShape;
private JTextField one;
private JLabel label;
private int count;
DrawingPanel drawPanel = new DrawingPanel();
public static void main (String[] args){
JFrame frame = new JFrame();
ShapePanel shape = new ShapePanel();
frame.getContentPane().add (new ShapePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public ShapePanel(){
JPanel controlPanel = new JPanel();
addShape = new JButton("Add Shape");
controlPanel.setPreferredSize (new Dimension(100, 400));
one = new JTextField();
controlPanel.add (addShape);
label = new JLabel ("Count:");
controlPanel.add (label);
controlPanel.add (one);
add(controlPanel);
add(drawPanel);
ButtonListener listener = new ButtonListener();
addShape.addActionListener (listener);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource() == addShape){
if(count < drawObjects.length){
count++;
one.setText(" " + count);
drawPanel.repaint();
}
}
}
}
private class DrawingPanel extends JPanel{
public DrawingPanel(){
setPreferredSize (new Dimension(400, 400));
setBackground (Color.pink);
}
}
public void paintComponent (Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < drawObjects.length; i++){
drawObjects[i].display(g);
}
}
}
I get an error of null at this line drawObjects.display(g) i also tried
for(Shape s : drawObjects)
s.display(g);