Some animations (such as some gif files) only store in each frame the pixels that change from the previous frame. To draw these animations correctly, you have to paint the first frame, then paint the succeeding frames on top of them without erasing the previous frames. JPanels, however, always redraw the background when you call repaint(), erasing the previous frames. Is there a way to prevent a JPanel from redrawing the background? I've been told that calling super.paintComponent(g)
in the JPanels paintComponent(Graphics g)
method is what redraws the background, but I tried commenting that out and it lead to some strange behaviour, so I'm assuming it does more than just repaint the background.

- 191
- 1
- 12
-
4Paint to a `BufferedImage`, display it in a `JLabel`. The image will retain all previous drawings. – Andrew Thompson Nov 18 '16 at 18:54
-
For [example](http://stackoverflow.com/a/3256941/230513). – trashgod Nov 18 '16 at 19:24
-
Another alternative is to draw the first image of the animation. On the next repaint, draw the first and second images of the animation. On the next repaint, draw the first, second, and third images of the animation. And so on. Yes, this is more work than drawing to a BufferedImage, but it's a practical solution in some animations. – Gilbert Le Blanc Nov 18 '16 at 23:11
2 Answers
I'd recommend to build your code upon the already existent code provided by the API instead of messing with it. Just store the image as BufferedImage
. This allows you to display it using an ImageIcon
, so it's an additional simplification. This allows you to update single pixels without any hassles with the API. If you absolutely insist on excluding the JPanel
from the repaint-routine, this question might help.
In general:
Follow the conventional use of the API. If you want to permanently store data of an image, us a BufferedImage
. JComponents
are supposed to be entirely overridden every time the frame is updated.

- 1
- 1
Depending on your exact requirement there are two common approaches:
- Draw on a BufferedImage and then display the BufferedImage
- Keep an ArrayList of Objects you want to paint and paint all the Objects in the list every time paintComponent() is invoked.
Check out Custom Painting Approaches for more information and working examples of each approach.

- 321,443
- 19
- 166
- 288