Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is SwingUtilities.invokeLater [duplicate]

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?

like image 551
11684 Avatar asked Aug 22 '12 16:08

11684


People also ask

What is SwingUtilities invokeLater?

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.

What is the difference between invokeAndWait and invokeLater?

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(); } });

What is SwingUtilities invokeLater new runnable ()?

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.

What is EventQueue invokeLater in Java?

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.


2 Answers

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...

like image 180
Kumar Vivek Mitra Avatar answered Sep 28 '22 07:09

Kumar Vivek Mitra


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.

like image 37
Marko Topolnik Avatar answered Sep 28 '22 07:09

Marko Topolnik