Java EventQueue

EventQueue is a platform-independent class that queues events, both from the underlying peer classes and from trusted application classes.

It encapsulates asynchronous event dispatch machinery which extracts events from the queue and dispatches them to the appropriate client program. The particular behavior of this machinery is implementation-dependent. The only requirements are that events which were actually enqueued to this queue (note that events being posted to the EventQueue can be coalesced) are dispatched:

Some browsers partition applets in different code bases into separate contexts, and establish walls between these contexts. In such a scenario, there will be one EventQueue per context. Other browsers place all applets into the same context, implying that there will be only a single, global EventQueue for all applets. This behavior is implementation-dependent. Consult your browser's documentation for more information.

Static Method invokeLater

The static method EventQueue.invokeLater(Runnable runnable) causes runnable to have its run method called in the dispatch thread of the system EventQueue. This will happen after all pending events are processed.

Threads

Every program has a set of threads where the application logic begins. In standard programs, there's only one such thread: the thread that invokes the main method of the program class. In applets the initial threads are the ones that construct the applet object and invoke its init and start methods; these actions may occur on a single thread, or on two or three different threads, depending on the Java platform implementation. We call these threads the initial threads.

In Swing programs, the initial threads don't have a lot to do. Their most essential job is to create a Runnable object that initializes the GUI and schedule that object for execution on the event dispatch thread. Once the GUI is created, the program is primarily driven by GUI events, each of which causes the execution of a short task on the event dispatch thread. Application code can schedule additionals tasks on the event dispatch thread (if they complete quickly, so as not to interfere with event processing) or a worker thread (for long-running tasks).

An initial thread schedules the GUI creation task by invoking EventQueue.invokeLater, which takes a single argument: the Runnable that defines the new task.

Why doesn't the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread.

Examples

Example 1: Test1, not using event dispatch thread.

Example 2: Test1, using an event dispatch thread.

References

textbook, page 286-287
Java API, see java.awt.EventQueue
Java tutorial on threads


Maintained by John Loomis, last updated 2 July 2007