Possible Duplicate:
What does SwingUtilities.invokeLater do?
SwingUtilities.invokeLater
I have seen this little piece of code hundreds of times:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
Now my question is: what does invokeLater()
do? What kind of bad things will happen if I just create and show my GUI inside the main thread?
An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities. invokeLater() method works like SwingUtilities. invokeAndWait() except that it puts the request on the event queue and returns immediately.
Their only difference is indicated by their names: invokeLater simply schedules the task and returns; invokeAndWait waits for the task to finish before returning. You can see examples of this throughout the Swing tutorial: SwingUtilities. invokeLater(new Runnable() { public void run() { createAndShowGUI(); } });
SwingUtilities class has two useful function to help with GUI rendering task: 1) invokeLater(Runnable):Causes doRun. run() to be executed asynchronously on the AWT event dispatching thread(EDT). This will happen after all pending AWT events have been processed, as is described above.
invokeLater. public static void 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.
1. Event Dispatcher Thread
is the GUI thread.
2. If you are talking about the main() method
...then its not long lived in Java Gui.
main()
method after scheduling the construction of GUI in EDT quits, now its EDT that handles the GUI.
3. invokeLater
means that this call will return immediately as the event is placed in Event Dispatcher Queue, and run()
method will run asynchronously...
Swing is not thread-safe and all changes to Swing objects must be performed within the Event Dispatch Thread. If you try to run your code outside it, you'll get unspecified behavior, which will probably become weird at some point.
In contrast, the SWT/JFace GUI framework that Eclipse uses asserts the correct thread on each public entry point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With