views:

58

answers:

2

I'm a little confused about the Swing painting model.

Suppose that I have a JComponent comp, and I do something like:

c.setBackground(Color.RED);
c.setBackground(Color.YELLOW);

Obviously, the end result is that the color is yellow.

How does Swing handle this?

Does the first call trigger an immediate repaint so there'll be a short flicker of red before the yellow? Is this sequence significantly slower than just a paint of yellow?

If I was running this from outside the Swing Event thread, I would assume that in most cases (though a race condition is possible), by the time the Swing EDT comes visiting the property is already set to yellow so there'll never be any red painted.

However, my understanding is that I should make these calls from inside a Runnable in the Swing EDT. Is that correct? In that case it would seem like the EDT would have to fully perform each change without any "lookahead"?

+4  A: 

The area of the window is marked dirty immediately. A paint request will later come back on the EDT. The OS or the event queue mechanism (or even the component) may merge repaint events (strictly a quality of implementation matter, but in practice repaints in the same window will be merged, even if they do not intersect).

Methods on Swing components should be called on the EDT. The Event Dispatch Thread belongs to AWT, not Swing.

Tom Hawtin - tackline
Tom, I'm a little confused. If I am running these two commands inside an invokeLater() or an invokeAndWait(), doesn't each one of them occur immediately? Or does Swing add extra invokeLaters() with its own instructions on the EDT? Also, is the EDT and the AWT dispatch thread the same thing?
Uri
if you are running inside invokeLater the whole block of code (in Runnable) will be executed on EDT. See my response above
eugener
If you use `invokeLater`/`invokeAndWait` the command get queued and executed on the same thread as the paints. `invokeLater`/`invokeAndWait` just add an `InvocationEvent` onto the AWT `EventQueue`.
Tom Hawtin - tackline
+2  A: 

First of all you should not make such calls outside of EDT. The results can be unpredictable. Since all Swing components are double-buffered you will see no flicker when doing this. In addition to that all consecutive repaint requests are joined into one when possible.

Overall, you shouldn't see any issues at all when doing this as long as it is done on EDT

eugener