I have defined a class called Stone to add graphical stones to a 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 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 toJPanel) and override thepaintComponentmethod (because you want some custom painting of your object).