Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing GUI by another thread in java (swing)

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.

like image 512
galica Avatar asked Aug 29 '11 11:08

galica


People also ask

How do you update Swing component from a thread other than EDT?

You can use invokeAndWait() and invokeLater() to update a Swing component from any arbitrary thread.

Is Java Swing multi threaded?

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.

What is SwingUtilities invokeLater () used for?

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 javax Swing SwingUtilities invokeLater?

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.


1 Answers

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
   ...
}
like image 115
unholysampler Avatar answered Oct 12 '22 03:10

unholysampler