Search code examples
javamultithreadingswingloopsupdating

Why is my ProgressBar not updating in a for() loop?


I have a JProgressBar progressBar which should update in a for() loop. Actually I already looked at this question: Progress bar not updating during a loop and I tried it with a new Thread, but I don't know why it still doesn't update.

What I tried:

    public void getNewUUID(BufferedWriter output) {
    Menu.progressBar.setMinimum(0);
    Menu.progressBar.setMaximum(100);
    String hashchar = "";
    x = ID_LENGTH/100;
    y=0;

    for(int ch = 0; ch != ID_LENGTH; ch++) {
        done = ch;
        hashchar = "";
        for(int id = 0; id < ID_LENGTH; id++) {
            hashchar = hashchar+ALPHA_CHARS[rnd.nextInt(ALPHA_CHARS.length)];

            try {
                output.write(hashchar);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            hashchar = "";

            new Thread(new Runnable() {
                public void run() {
                    if(done>=x) {
                        x=x+x;
                        y++;
                        Menu.progressBar.setValue(y);

                    }
                }
            }).start();
        }



    }

try {
    output.flush();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
try {
    output.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

Solution

  • You are performing the progress bar update on a non UI thread. You will need to use SwingUtilities.invokeLater(Runnable r):

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    if(done>=x) {
                        x=x+x;
                        y++;
                        Menu.progressBar.setValue(y);
    
                    }
                }
            });
    

    This should make sure that the progress bar update takes place on the UI thread, which should cause the progress bar to be refreshed with the new values.