I have this program where when I click start, it starts painting rectangles one on top of the other by storing each rectangle created by paintComponent in an array and then displaying them on the screen.
When I click stop, the animation stops.
This is all fine and dandy but I have been banging my head against the computer to create a way where when I hit start after hitting stop, it would clear the screen and start the animation anew. I am pasting my code below, any help will be greatly appreciated.
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.*;
public class TwoButtonsRandomRec {
JFrame frame;
Timer timer;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TwoButtonsRandomRec test = new TwoButtonsRandomRec();
test.go();
}
});
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton startButton = new JButton("Start");
startButton.addActionListener(new StartListener());
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
final DrawPanel myDraw = new DrawPanel();
timer = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
myDraw.repaint();
}
});
frame.add(startButton, BorderLayout.NORTH);
frame.add(stopButton, BorderLayout.SOUTH);
frame.add(myDraw, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
class StartListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
timer.start();
}
}
class StopListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
timer.stop();
}
}
class DrawPanel extends JPanel {
ArrayList<MyRectangle> rects = new ArrayList<>();
Random rand = new Random();
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
addRect();
for(MyRectangle r : rects) {
g.setColor(r.getColor());
g.fillRect(r.x, r.y, r.width, r.height);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
public void addRect() {
int ht = rand.nextInt(getHeight());
int wd = rand.nextInt(getWidth());
int x = rand.nextInt(getWidth() - wd);
int y = rand.nextInt(getHeight() - ht);
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
}
}
}
class MyRectangle extends Rectangle {
Color color;
public MyRectangle(int x, int y, int w, int h, Color c) {
super(x, y, w, h);
this.color = c;
}
public Color getColor() {
return color;
}
}