I would like to make JProgressBar in new JDialog, witch will be in separate thread from main logic. So I can start indeterminate progress with just creating new JDialog and completing that progress with disposing JDialog. But it gives me hard time to achieve that because after JDialog appears it doesn’t show any components (including JProgressBar) until the logic in main thread (SwingUtilities) is done.
Thread including JDialog:
package gui.progress;
public class ProgressThread extends Thread {
private ProgressBar progressBar = null;
public ProgressThread() {
super();
}
@Override
public void run() {
progressBar = new ProgressBar(null);
progressBar.setVisible(true);
}
public void stopThread() {
progressBar.dispose();
}
}
JProgressBar toggle method:
private static ProgressThread progressThread = null;
...
public static void toggleProcessBar() {
if(progressThread == null) {
progressThread = new ProgressThread();
progressThread.start();
} else {
progressThread.stopThread();
progressThread = null;
}
}
you have issue with Concurrency in Swing, Swing is single threaded and all updates must be done on EventDispatchThread, there are two ways
easies to use
Runnable#Thread, but output to the Swing GUI must be wrapped intoinvokeLateruse SwingWorker, example about
SwingWorkeris in the Oracles JProgressBar and SwingWorker tutorialEDIT
this code simulate violating EDT and correct workaround for SwingWorker too