
TheEvent Dispatch Thread
For efficiency reasons, Swing components are not designed to be thread safe. This
means that Swing components should be manipulated by a single thread at a time.
The easiest way to ensure this is to do all your GUI manipulations from the event
dispatch thread. Every GUI application has an event dispatch thread: it is the
thr ead that waits for events to occur and then dispatches those events to the
appr opriate event handlers. All of your event listener methods are invoked by the
event dispatch thread, so any GUI manipulations you perfor m fr om an event lis-
tener are safe.
Ther e ar e times, however, when you need to update your UI in response to some
kind of external event, such as a response from a server that arrives in a separate
thr ead. To accommodate these situations, Swing provides two utility methods that
allow you ask the event dispatch thread to run arbitrary code. The methods are
SwingUtilities.invokeLater() and SwingUtilities.invokeAndWait().You pass
a
Runnable object to each method, and the run() method of this object is invoked
fr om the event thread.
invokeLater() retur ns right away, regardless of when the
run() method is invoked, while invokeAndWait() does not retur n until the run()
method has completed.
The
invokeLater() and invokeAndWait() methods do not run your Runnable
object right away. Instead, each method encapsulates the Runnable object within a ...