What does SwingUtilities.invokeLater
do? Is it just delaying the execution of a block of codes inside its run
method? What is the difference between calling an action within the invokeLater
function or simply calling it at the end of the thread we want to be executed? Can anyone help me with what really does the invokeLater
function do?
As other answers have said, it executes your Runnable
on the AWT event-dispatching thread. But why would you want to do that? Because the Swing data structures aren't thread-safe, so to provide programmers with an easily-achievable way of preventing concurrent access to them, the Swing designers laid down the rule that all code that accesses them must run on the same thread. That happens automatically for event-handling and display maintenance code, but if you've initiated a long-running action - on a new thread, of course - how can you signal its progress or completion? You have to modify a Swing control, and you have to do it from the event-dispatching thread. Hence invokeLater
.
It will run the piece of code on the AWT thread. Which lets you modify the GUI from other threads.
From Docs:
Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI.
As already noted, InvokeLater allows you to safely call methods in swing classes when you are not running on the EventQueue to begin with. However, you can simplify your code and your life by accessing other fields and classes only from the EventQueue. They can work with swing and each other without all the hassles of multi-threading. If you have started another thread, use InvokeLater to get back to the EventQueue as quickly as possible and minimize the number of fields that must be synchronized or otherwise guarded.
If you need to make the most of multiple cores you will have to reduce your use of the EventQueue, and you will have to pay a big price in complexity.
that's would be Comment, but looks like as longer as..., just basic stuff
1/ create own EDT for correct update to the GUI, f.e. if you are executed some code by using plain vanilla Thread, java.util.Timer, Executor .. more here
2/ helps with set Focus to the JComponents iof there are some Listeners because if is there f.e. DocumentListener then you hard to set Focus
to the desired JComponents
3/ delay code executions block and move that to the ends of EDT
Note that you eventually get a call to your doRun.run( ) method for every time you call invokeLater(doRun). So if you call it ten times before the event thread gets an opportunity to perform its processing, you are likely to then get ten successive calls to doRun.run( ).
© 2022 - 2024 — McMap. All rights reserved.