As we mentioned at the beginning of the book, there is a significant multithreading issue with Swing. The fundamental rule is this: once a component has signaled its intent to be repainted, all updates to the component’s state should be done in the event dispatch thread. A component has signaled its intention to be painted or repainted when any of the following methods are invoked on it:
While the last method,
pack(), does not perform a
repaint, it does invalidate a component, recalculating its size and
modifying its dimensions accordingly.
By confining updates of the component state to the event dispatch
thread, you keep changes in sync with the repainting requests of the
RepaintManager, and avoid potential race
It’s important to understand when you need to worry about this and when you do not. In most situations, you’ll be updating the state of your user interface in response to various user events. If this is the case, you can freely update your components, since your event-handling methods (in your listeners) will automatically be invoked in the event dispatch thread.
The only time you have to worry about updating the state of a Swing component is when the request for the update comes from some other thread. An example of such a situation would be events driven by some outside process responsible for notifying your application when something changes. For example, say you ...