Java – how to add visual content to JPanel?

I have defined a class named stone to add graphic blocks to JPanel:

public class Stone {

    private int x,y;
    private Color color;

    private static final int radius = 18;

    Stone(Color color) {
        this.color = color;
    }

    public Stone(int x,int y,Color color) {
        this(color);
        this.x = x;
        this.y = y;
    }

    void draw(Graphics g) {
        g.setColor(color);

        g.fillOval(x - radius,y - radius,2 * radius,2 * radius);
    }

    void setX(int x) {
        this.x = x;
    }

    void setY(int y) {
        this.y = y;
    }
}

I want to draw them on JPanel Do I have to do this in the paint method of JPanel, or can I use the add method of JPanel?

Solution

A quick answer is that you should extend a JComponent (because you want to add it to JPanel) and override the paintcomponent method (because you want some custom object painting)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>