How to paint an arrayList of shapes Java

走远了吗. 提交于 2019-11-29 18:49:30

super.paintComponent(g) invokes the paintComponent method from the superclass of JPanel (the JComponent class) to erase whatever is currently drawn on the panel. This is useful for animation, but not for setting color.

I guess you'll have to set the color of the shapes in your Arraylist<Shape> shapes when you will create them, nonetheless it could be helpfull to see the Shape class. Maybe you could create a function changeColor(Color ColorToBeSet) in this shape class and loop through the shapes ArrayList to call it at the end of your ShapeListener

You could...

Define an "abstract" concept of a shape, which has the basic properties (location and size) and which can paint itself...

public abstract class Shape {

    private int x, y;
    private int width, height;
    private Color c;

    public Shape(int x, int y, int width, int height, Color c) {
        this.x = x;
        this.y = y;
        this.c = c;
        this.width = width;
        this.height = height;
    }

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Color getColor() {
        return c;
    }

    public abstract void paint(Graphics2D g2d);
}

Then you can implement the individual shapes...

public class Rectangle extends Shape {

    public Rectangle(int x, int y, int width, int height, Color c) {
        super(x, y, width, height, c);
    }

    @Override
    public void paint(Graphics2D g2d) {
        g2d.setColor(getColor());
        g2d.drawRect(getX(), getY(), getWidth(), getHeight());
    }
}

public class Oval extends Shape {

    public Oval(int x, int y, int width, int height, Color c) {
        super(x, y, width, height, c);
    }

    @Override
    public void paint(Graphics2D g2d) {
        g2d.setColor(getColor());
        g2d.drawOval(getX(), getY(), getWidth(), getHeight());
    }
}

Then, you can simply call the paint method of each instance of Shape as required...

public class TestPane extends JPanel {

    private List<Shape> shapes;

    public TestPane() {
        shapes = new ArrayList<>(25);
        shapes.add(new Rectangle(10, 10, 20, 20, Color.RED));
        shapes.add(new Oval(15, 15, 40, 20, Color.RED));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Shape shape : shapes) {
            Graphics2D g2d = (Graphics2D) g.create();
            shape.paint(g2d);
            g2d.dispose();
        }
    }

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!