Refreshing GUI by another thread in java (swing)
Solution 1:
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
...
}
Solution 2:
If you make the status
field thread safe, then you can call setStatus
directly from your background thread. To make the status thread-safe, put changes in a synchronize block, and make the variable volatile so updates on other threads become visible.
E.g.
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 in place, it's ok to call setStatus
from any thread.