I am keen to learn how I can finish this project. I want to draw three random shapes in random colors and positions and add them to the list (which later need to be played in the second window).
Here is what I have:
public
class Frame extends JFrame { // here was implements Runnable when i
// used Thread
public ArrayList<MyShape> shapesList = new ArrayList<MyShape>(30); // create list
public JPanel shapePanel;
public Timer timer;
public final int NEW_SHAPE_FREQUENCY = 1000;
public Rectangle myRect;
public Oval myOval;
public Line myLine;
public Frame() {
super("I do not need title, just 50%");
setSize(800, 600);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setVisible(true);
setLayout(new BorderLayout());
shapePanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (MyShape s : shapesList) {
g.setColor(myOval.color); // in this line i have
// Exception: NullPointerException
g.fillRect(((int)(getWidth()*Math.random()*0.8d)),((int)
(getHeight()*Math.random()*0.8d)), (int) (myRect.x2),(int) myRect.y2);
}
}
};
add(shapePanel);
initTimer();
// Thread t0 = new Thread(this); // How can i use Threads in this case ??
// t0.start();
}
private void initTimer() {
timer = new Timer(NEW_SHAPE_FREQUENCY, e -> {
shapesList.add(new MyShape()); // Add a new shape to the arraylist
shapePanel.repaint(); // Repaint the panel, so the new shape is
// visible
});
timer.start();
}
/*
@Override
public void run() {
while (true) {
try {
Random rand = new Random();
switch (rand.nextInt(3)+1) {
case 1:
shapesList.add((Shape)myRect);
break;
case 2:
shapesList.add((Shape)myOval);
break;
case 3:
shapesList.add((Shape)myLine);
break;
}
repaint();
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
*/
}
After modification, the Frame class now looks like this. I am newbie with coding in Java sorry about this errors