I am making a JPanel that needs to add colored squares as the user interacts with it.
public class Corkboard extends JPanel {
Color colour = Color.RED;
Graphics gr;
int x = 20;
int y = 20;
public Corkboard() {
setBorder(new LineBorder(new Color(153, 51, 0), 5));
setBounds(0, 0, 470, 361);
setBackground(new Color(225, 200, 150));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(colour);
g.fillRect(x, y, 70, 70);
}
public void blueShift() {
colour = Color.blue;
x = (int) (Math.random() * 300);
y = (int) (Math.random() * 200);
repaint();
}
}
I connected the blueshift() method to an ActionListener on the JFrame class, so I know how to change the color and position on command, but I can't figure out how to add new squares without removing the first once the program has started running.