开发者

How to add something visual to a jpanel?

I have defined a class called Stone to add graphical stones to a JPanel:

public class Stone {

    private int x, y;
    private Color color;
开发者_StackOverflow
    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 a JPanel. Do I have to do this within the paint method of JPanel or is it possible to use the add method of JPanel?


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 painting of your object).


The easiest thing to try is to make your Stone class extend JComponent, rename draw() to paintComponent() and add a Stone instance to your JPanel.


It depends on what you want to do with it on the screen. As the others mentioned you could inherit from JComponent, which could be a good choice if the user wants to interact with it in some way.

A more light-weight approach could be to implement the Shape interface, or provide a method getShape().

You could use the ShapeIcon I wrote some time ago, to add it to a JLabel: http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/icon/ShapeIcon.html

Then add the JLabel to the JPanel.

But maybe instead of adding individual Stone icons to individual JLabels, you want to draw an image first and show that in the JPanel?

If you could tell us more about your goals we could help you better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜