Search code examples
javaswingpaintcomponent

Java: How to fill shape from an ArrayList with color?


I have an ArrayList of Shapes (Rectangles and Ovals) and I want to paint these shapes. How do I fill them with color in the for loop?

My ArrayList is composed of both Rectangles and Ovals. If I do fillRect(color), it paints all shapes as Rectangles, and if I do fillOval(color), it paints all shapes as Ovals. How can I fill the Ovals and Rectangles appropriately? The code below only does the outlines.

private ArrayList<Shape> shapes = new ArrayList<Shape>();
private Shape currentShape; // the shape being drawn (either Rectangle or Oval)

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    for(Shape s : shapes) {
        Graphics2D g2d = (Graphics2D) g.create();
        s.paint(g2d);
    }
}

Solution

  • Graphics2D.fill(Shape) will do.

    private List<Shape> shapes = new ArrayList<>();
    
    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.RED);
        for (Shape shape : shapes) {
            g2d.fill(shape);
        }
    }
    

    No g.create. The fact that every paintComponent parameter is actually a Graphics2D is historically founded: they replaced Graphics by a more exhaustive Graphics2D, but for backward compatibility kept Graphics.