Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwingUtilities.invokeLater

My question is related to SwingUtilities.invokeLater. When should I use it? Do I have to use each time I need to update the GUI components? What does it exactly do? Is there an alternative to it since it doesn't sound intuitive and adds seemingly unnecessary code?

like image 500
FadelMS Avatar asked Aug 25 '11 20:08

FadelMS


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 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 the difference between InvokeAndWait and invokeLater?

Difference on InvokeLater vs InvokeAndWait in Swing 1) InvokeLater is used to perform a task asynchronously in AWT Event dispatcher thread while InvokeAndWait is used to perform task synchronously. 2) InvokeLater is a non-blocking call while InvokeAndWait will block until the task is completed.

What is EventQueue invokeLater?

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 Answers

Do I have to use each time I need to update the GUI components?

No, not if you're already on the event dispatch thread (EDT) which is always the case when responding to user initiated events such as clicks and selections. (The actionPerformed methods etc, are always called by the EDT.)

If you're not on the EDT however and want to do GUI updates (if you want to update the GUI from some timer thread, or from some network thread etc), you'll have to schedule the update to be performed by the EDT. That's what this method is for.

Swing is basically thread unsafe. I.e., all interaction with that API needs to be performed on a single thread (the EDT). If you need to do GUI updates from another thread (timer thread, networking thread, ...) you need to use methods such as the one you mentioned (SwingUtilities.invokeLater, SwingUtilities.invokeAndWait, ...).

like image 97
aioobe Avatar answered Sep 30 '22 08:09

aioobe