Swing event-handling and painting code executes in a single thread, called the
event-dispatching thread
. This ensures that each event handler finishes executing before the next one executes and that painting isn't interrupted by events. To avoid the possibility of deadlock, you must take extreme care that Swing components and models are created, modified, and queried
only
from the event-dispatching thread.
Note: We used to say that you could create the GUI on the main thread as long as you didn't modify components that had already been realized. [PENDING: The following red text belongs in a footnote.] Realized means that the component has been painted onscreen, or is ready to be painted. The methodssetVisible(true)
andpack
cause a window to be realized, which in turn causes the components it contains to be realized. While this worked for most applications, in certain situations it could cause problems. Out of all the demos in the Swing Tutorial, we encountered a problem only in ComponentEventDemo. In that case, sometimes when you launched the demo, it would not come up because it would deadlock when updating the text area if the text area had not yet been realized, while other times it would come up without incident.To avoid the possibility of thread problems, we recommend that you use
invokeLater
to create the GUI on the event-dispatching thread for all new applications. If you have old programs that are working fine they are probably OK; however you might want to convert them when it's convenient to do so.