I wrote a code in Java (using swing) which draws few polygons on a panel.
public MyClass extends JPanel
The code is very simple (but long) and basically adds few Polygons, then adds few points to each polygon and then draw them on the screen (with drawPolygon).
My problem is when I run the program, I can’t see the drawings on the panel.
After a while, I figure out that when I re-size my frame, I can suddenly see the drawing but it duplicates itself many times (depends how much I re-size). If I play enough time with the resizing, I get:
java.lang.OutOfMemoryError: Java heap space
Also, myPolygon.invalidate() doesn’t help.
When using setResizable(false) I can’t see my drawing at all.
Does anyone have a solution?
Duplicate Image Screenshot:1
To start with, in your
paintComponentmethod, don’t callThis will request a repaint, cause
paintComponentto be recalled and you’ll end up in a nasty loop, consuming your CPU and (as you have found out), your memory.IF you can get away with it, you’re better off to draw the polygon to a buffer and draw the buffer to the screen on each iteration of the
paintComponent. This will be faster in the long run…UPDATE
So, anyway, the other fun things you’re doing are…
paintComponentwas called)paintComponentwas calledTry something like this instead