Matthew Flynn
Matthew Flynn

Reputation: 191

Prevent JPanel from redrawing background on repaint() calls

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.

Upvotes: 0

Views: 902

Answers (2)

camickr
camickr

Reputation: 324118

Depending on your exact requirement there are two common approaches:

  1. Draw on a BufferedImage and then display the BufferedImage
  2. 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.

Upvotes: 1

user4668606
user4668606

Reputation:

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.

Upvotes: 3

Related Questions