views:

112

answers:

2

If I have a bunch of custom JComponents in a Swing panel, and each of them can contain many other JComponents, is there a way to "freeze" repaints on the top level components and then unfreeze them, triggering a repaint?

I guess I am trying to do sort of a localized double-buffering.

+1  A: 

Overriding paint(Graphics) to not do anything if a flag is set will prevent the painting from happening; you can also add your own double buffering by overriding to draw to a image.

You can enable double buffering on a per swing JComponent basis using that component's setDoubleBuffered(boolean) method, you don't need to do anything else if that's all you need.


Even if you disable painting at the top level component by overriding paint, it won't stop child components from painting if they are receiving events; you could replace the frame's contents with a static image ( created from calling paint with the graphics from a buffered image ).

Pete Kirkham
it's better to override paintComponent() method.And, if you just return from paintComponent(), will it keep previous image or just leave garbage?
tulskiy
Not always. paint calls paintComponent() and paintChildren() passing in the graphics for the off-screen buffer if double-buffering is enabled. If you want to change how a component paints itself without changing the behaviour of children, borders or double-buffering, then it's better to override paintComponent(), but that isn't what is being asked for here.
Pete Kirkham
+1  A: 

Also, just in case the reason you're doing this is because you are doing a bunch of GUI updates to components and are worrying about all of those automatically posted repaints(), don't. repaint() does not paint immediately, it posts a deferred repaint event to the AWT event queue, which will coalesce multiple repaints for a given region to avoid doing the same painting over and over.

CarlG
Our problem is that we send enough of these events to hog the event thread to a point where the UI becomes unresponsive to user input. The only solution we found is to sleep between some updates, to give user interaction a chance to squeeze in, but we pay a cost. I'm trying to test whether somehow freezing and unfreezing can hasten things up a little.
Uri
Are these updates in response to user events (EDT), or to non-swing events (eg background thread)?
Devon_C_Miller
Can you narrow down whether it is data processing occurring in the EDT or the actual repainting that is taking the time?
CarlG