I trying to create a JPanel that draws rectangles. The Panel needs to draw alot of rectangles, but they dont move.
One solution to my problem was to create an list with all the rectangles i already created and draw they all in every call of “Paint”. But there is a lot of rectangles and it slows the computer.
I also tried to use repaint(x, y, height, width) to rapaint just the space of the new rectangle but it did not work. (JPanel keeps erasing previous rectangles.)
In sort, i need to draw rectangles that wont disappear every paint. Or a paint method that wont erase previous draws, or wont paint the background.
That is part of my JPanel class:
class MyPanel extends JPanel{
private int x, y, size;
private Color c;
public void DrawRect(int x, int y, int size, Color c){
this.x = x;
this.y = y;
this.size = size;
this.c = c;
repaint();
}
@Override
public void
paint(Graphics g) {
g.setColor(c);
g.fillRect(x, y, size, size);
}
}
paintWITHOUT VERY, VERY good reason…usepaintComponentinsteadsuper.paintXxx, these methods do a lot in the background, failing to call super is only going to come back and haunt you.MyPaneltransparent.Paint’s are stateless. There is no connection between the last paint and the next. On each paint request you are expected to update the entire state.
Andrew’s suggest of double buffering (or back buffering) is and excellent one, and I highly encourage you to have a look an implementing it.
In the mean time, I put this little example together…
Basically, you press and hold the mouse button and it will randomly add another rectangle to the panel every 40 milli-seconds (roughly 25 frames a second).
I got this up to a 1000 rects without any issue, was able to resize the window without and issue or obviously slow down…
have a go, it’s fun 😉
ps- I got to up to over 5000 rectangles before I noticed a slow down (I modified the code down to a 10 milli second delay and was adding 10 new rectangles per tick)