SwingUtilities.invokeLater
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, ...).
Swing is single threaded and all changes to the GUI must be done on EDT
Basic usage for invokeLater()
Main methods should be always wrapped in
invokeLater()
Delayed (but asynchronously) action/event to the end of
EventQueue
,If EDT doesn't exists then you have to create a new EDT by using
invokeLater()
. You can test it withif (SwingUtilities.isEventDispatchThread()) {...
There exists
invokeAndWait()
, but till today I (just my view) can't find a reason for usinginvokeAndWait()
instead ofinvokeLater()
, except hard changes into GUI (JTree & JTable), but just with Substance L&F (excellent for testing consistency of events on the EDT)Basic stuff: Concurrency in Swing
All output from background tasks must be wrapped in
invokeLater()
Every Swing application has at least 2 threads:
- The main thread that executes the application
- The EDT (Event Dispatching Thread) is a thread that updates the UI (so the UI will not freeze).
If you want to update the UI you should execute code within the EDT.Methods like SwingUtilities.invokeLater, SwingUtilities.invokeAndWait, EventQueue.invokeLater, EventQueue.invokeAndWait allow you to execute code by the EDT.