Search code examples
javamultithreadingswingevent-dispatch-threadjprogressbar

Why does my JFrame not update


I have this piece of code of a JFrame that will show the user the progress during the importing time of images:

public class LoadFrame implements Runnable {

    JProgressBar progressbar;
    JPanel loadpanel;
    MainScreen mainscreen;
    int progress;
    JDialog mainloadframe;

    public LoadFrame(String operation) {

        mainloadframe = new JDialog();
        JLabel operationlabel = new JLabel(operation);
        progressbar = new JProgressBar(0, 100);
        loadpanel = new JPanel();

        mainloadframe.setSize(300, 75);
        mainloadframe.setLocationRelativeTo(null);
        mainloadframe.setLayout(new GridLayout(1, 2));
        mainloadframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        mainloadframe.setAlwaysOnTop(true);
        mainloadframe.setTitle(operation);
        mainloadframe.setVisible(true);

        progressbar.setValue(0);
        progressbar.setStringPainted(true);
        loadpanel.add(progressbar);
        loadpanel.add(operationlabel);
        mainloadframe.add(loadpanel);

    }

    public void setMainScreen(MainScreen mainscreen) {
        this.mainscreen = mainscreen;
    }

    public void disposeLoadFrame() {
        mainloadframe.dispose();
    }

    public void setProgress(int progress) {
        this.progress = progress;
    }

    @Override
    public void run() {
        while (progress != 100) {
            progressbar.setValue(progress);
        }
    }
}

the actual calculating of the progress is also done in an thread, but for some reason the progressbar doesn't show up on the JFrame till the moment the images are done importing. I'm pretty sure it is a Thread problem but I can't seem to figure it out. A little help would be appreciated.


Solution

    • Runnable#Thread isn't start()

    • (post to the forums) have to add Thread.sleep(int) into run(), then progressbar.setValue(progress); mest be wrapped into invokeLater()

    • by using util.Timer instead of Runnable#Thread , then progressbar.setValue(progress); mest be wrapped into invokeLater()


    • by using Swing Timer

    • proper of ways is invoke progressbar.setValue(progress); from SwingWorker