1

I know that JPanel is, by default, automatically double-buffered. However, I have a particularly time-intensive painting operation in my panel, but the panel only needs to be repainted when the underlying data changes, which is rare. Therefore, I'd like to reuse the JPanel buffer instead of having it clear after every call to repaint().

I've manually implemented a "dirty" flag on my JPanel subclass, but I have no idea how to cancel a paint operation once it's been started. I can't avoid the call to repaint in the first place, since my panel is inside a JScrollPane, which is being repainted every time it's resized (which does happen frequently), which causes my custom panel to be repainted.

Is there any way to do this without manually buffering the panel? If not, what's the recommended method for implementing a manual buffer in conjunction with a JPanel?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Alexis King
  • 43,109
  • 15
  • 131
  • 205
  • You can save the contents of the `JPanel` in a `BufferedImage` , and use it for displaying instead of recalculating the image at every repaints. – Extreme Coders May 10 '13 at 05:43
  • @ExtremeCoders Though it is possible to [get an image of a component](http://stackoverflow.com/a/5853992/418556), it is not simple. Showing an image in a label is a way to get a GUI with a preferred size that does not need to extend anything. And since you have the image, you might as well paint it directly. – Andrew Thompson May 10 '13 at 06:04

1 Answers1

4

I have a particularly time-intensive painting operation .. only needs to be repainted when the underlying data changes, which is rare..

Paint the data to a BufferedImage, display it in a JLabel. Call label.repaint() if it changes. E.G. as seen in this answer.

Bonus Showing an image in a label is a way to get a GUI with a preferred size, that does not need to extend anything. To get the perfect size for the frame or dialog that displays it, call pack().

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • @mKorbel Thanks! I thought that to upgrade it to an answer, it needed an extra effort. The image was obvious, as were the links, combined with part of the last comment. :) – Andrew Thompson May 10 '13 at 06:38