Updating GUI with another thread in java (swing)

I have a main program in which the GUI is based on swing and depending on one of the 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 update the GUI, it only calls updateGUI with the appropriate parameter, and everything is fine. But the program also creates an additional stream, which, after processing the corresponding data, should change the main GUI program. Unfortunately, I cannot call the updateGUI (..) method in this thread.

I know that I can use invokeLater or SwingWorker to update, but there are more than 10 elements, so I would rather use the udpateGUI () method.

I would be grateful for any hint.

+6
source share
2 answers

If the status stream is safe, you can call setStatus directly from the background stream. To make a thread thread safe, place the changes in the synchronization block and make the variable volatile so that updates are displayed on other threads.

eg.

 public class Frame extends JFrame implements Runnable { private volatile Status status = 1; ... @Override public void run() { switch (status) { case 1: ... case 2: ... } public void updateGUI(Status status) { setStatus(status); SwingUtilities.invokeLater(this); } private synchronized void setStatus(Status status) { this.status = status; } 

With these changes, it is normal to call setStatus from any thread.

+7
source

Here is a small snippet that you can add to a method that provides its execution in 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 ... } 
+16
source

Source: https://habr.com/ru/post/896118/


All Articles