home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book Home Java Enterprise in a Nutshell Search this book

3.6. The Event 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 thread that waits for events to occur and then dispatches those events to the appropriate event handlers. All of your event listener methods are invoked by the event dispatch thread, so any GUI manipulations you perform from an event listener are safe.

There are 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 thread. 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 from the event thread. invokeLater() returns right away, regardless of when the run() method is invoked, while invokeAndWait() does not return 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 special event object and places the event on the event queue. Then, when all pending events have been handled, the Runnable object is extracted from the event queue and the event dispatch thread calls its run() method. This means that invokeLater() provides a useful way to defer the execution of some chunk of code until after all pending events have been processed. There are times when you may even want to do this with code that is already running within the event dispatch thread.

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.