Executing Code in The EDT
Other application threads can have code executed in the event dispatching thread by defining the code in a Runnable
object and pass it to the SwingUtilities
helper class or to the EventQueue
. Two methods of these classes allow:
- synchronous code execution (
SwingUtilities.invokeAndWait(Runnable)
orEventQueue.invokeAndWait(Runnable)
) - and asynchronous code execution (
SwingUtilities.invokeLater(Runnable)
orEventQueue.invokeLater(Runnable)
)
from the EDT.
The method invokeAndWait
should never be called from the event dispatching thread—it will throw an exception. The method SwingUtilities.isEventDispatchThread
or EventQueue.isDispatchThread
can be called to determine if the current thread is the event dispatching thread.
Another solution for executing code in the EDT is using the worker design pattern. The SwingWorker
class, developed by Sun Microsystems, is an implementation of the worker design pattern, and as of Java 6 is part of standard Swing distribution. The open source project Foxtrot provides another synchronous execution solution similar to SwingWorker
.
Read more about this topic: Event Dispatching Thread
Famous quotes containing the words executing and/or code:
“Christs crucifix shall be made an excuse for executing criminals.”
—William Blake (17571827)
“Motion or change, and identity or rest, are the first and second secrets of nature: Motion and Rest. The whole code of her laws may be written on the thumbnail, or the signet of a ring.”
—Ralph Waldo Emerson (18031882)