To increase efficiency and decrease complexity, all Swing components are designed not to be thread-safe. This simply means that all access to Swing components needs to be done from a single thread. That thread is called the event-dispatch thread, and it isn't one you create yourself. If you are unsure that your executing code is in the event-dispatch thread, you can query the EventQueue class through its static isDispatchThread() method. Alternatively, you can query the SwingUtilities class through its static isEventDispatchThread() method. The isEventDispatchThread() method acts as a proxy to the isDispatchThread() method.
To properly execute tasks on the event-dispatch thread, implement the Runnable interface and pass the tasks to the EventQueue class. Use the public static void invokeLater(Runnable runnable) method of EventQueue if you need to execute a task on the event-dispatch thread, but you don't need any results and you don't care when the task finishes. However, if you can't continue what you're doing until the task completes and returns a value, use the public static void invokeAndWait(Runnable runnable) method of EventQueue. With invokeAndWait(Runnable runnable), you need to provide the code to get the return value -- it is not returned by the invokeAndWait() method.
If you're familiar with the SwingUtilities class, you know that it too has invokeLater() and invokeAndWait() methods. However, those two methods simply wrap the call to the EventQueue versions. So, it's better to directly call the EventQueue versions.
You need to access Swing components from the event-dispatch thread for both realized (visible) and unrealized (invisible) components. It might seem reasonable to access unrealized components from a thread other than the event-dispatch thread. However, because building a Swing GUI can trigger notification of listeners (such as for a property change event or when adding an ancestor component), and that notification is on the event-dispatch thread, it is always best to access Swing components from the event-dispatch thread.
This requirement of all access on the event-dispatch thread makes it interesting to create Swing programs. That's because the first things the main() method of a program does is create a Runnable object, create a JFrame, and put of all the components into that frame:
Runnable runnable = new Runnable() {
public void run() {
// build screen
}
}
EventQueue.invokeLater(runnable);
http://java.sun.com/developer/JDCTechTips/2005/tt0419.html
Nessun commento:
Posta un commento