Don't use getGrapchic()
. You need to learn the basics of custom painting. See Performing Custom Painting. Basically what you want to do is override paintComponent
and do your painting there.
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
// draw here.
}
When ever you repaint()
the panel, the paintComponent
will be implicitly called. So you could do something like
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (Rectangle2D rect: rectangles) {
g2.fill(rect);
}
}
You could then, for instance, add a new Rectangle2D
object to the List<Rectangle2D> rectagles
, and there would be another rectangle drawn on the canvas.
Also you may want to look at this answer, which shows how you can create the shape by dragging the mouse
The code in the example only uses one rectangle, but you could easily modify it to draw a List
of rectangles. And every time the mouse is pressed, it will add a new rectangle to the list, while still allowing you to drag the mouse to size the current rectangle obtained from the mouse press. Examine the link. Hope it helps.