0

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
FoxVocs
  • 41
  • 5
  • 4
    *but I can't figure out how to add new squares without removing the first once* - one way is to keep an ArrayList of each shape you want to paint. Then your painting method iterates through the ArrayList to paint each shape. See the `DrawOnComponent` example from [Custom Painting Approaches](https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/) for an example to get you started. – camickr Oct 21 '21 at 04:40
  • See an [example](https://stackoverflow.com/a/64426717/3992939) of the approach recommended by @camickr – c0der Oct 21 '21 at 05:13
  • putting the shapes into an ArrayList and using repaint() did it! Thank you so much! – FoxVocs Oct 21 '21 at 07:06

0 Answers0