I have a main program, in which GUI is based on swing and depending on one of four states the GUI elements have different parameters.
public class Frame extends JFrame implements Runnable {
Status status = 1;
...
@Override
public void run() {
switch (status) {
case 1:
...
case 2:
...
}
public void updateGUI(Status status) {
this.status = status;
SwingUtilities.invokeLater(this);
}
And if I want to refresh the GUI invokes only updateGUI with appropriate parameter, and everything is fine. But the program also creates an additional thread, which after processing the relevant data should change the GUI main program. Unfortunately I can not in this thread call the method updateGUI (..).
I know that I can use invokeLater or SwingWorker to refresh but there are more than 10 elements so I would rather use the method udpateGUI ().
I will be grateful for any hint.
You can use invokeAndWait() and invokeLater() to update a Swing component from any arbitrary thread.
This means that most Swing components are, technically, not threadsafe for multithreaded applications. Now don't panic: it's not as bad as it sounds because there is a plan. All event processing in AWT/Swing is handled by a single system thread using a single system event queue. The queue serves two purposes.
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.
The invokeLater() is a method in java on swing package and belongs to the SwingUtilities class. Invokelater is used by java swing developer to update or perform any task on Event dispatcher thread asynchronously. invokeLater has been added into Java API from swing extension and it belongs to SwingUtilities class.
Here is a little snippet you can add to a method to ensure it executes in the the GUI thread. It relies on isEventDispatchThread()
.
public void updateGUI(final Status status) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateGUI(status);
}
});
return;
}
//Now edit your gui objects
...
}
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