ProgressBar doesn't change its value in Java

13,847

The value of the progress bar is really updated. But it isn't simply on the screen yet. Often, we use progress bars in loops. But, while you are in the loop, which you probably invoked by clicking a button it isn't painted. Why? Because you invoked it by clicking a button. When you click a button, all the code you've made for that button is being executed by the AWTEventThread. This is the same thread that keep track of all the Swing components, and checks wether they have to be repainted. That is the thread that makes your JFrame come alive. When you hover a button and the color changes a bit, it's done by the AWTEventThread.

So, while you are working in the loop, the AWTEventThread can't update the screen anymore.

This means there are two solutions:

  1. (Recommend) You should create a separate thread which executes the loop. This means the AWTEventThread can update the screen if necessary (when you call bar.setValue(...);)

    public void yourButtonClickMethod()
    {
        Runnable runner = new Runnable()
        {
            public void run() {
            //Your original code with the loop here.
            }
        };
        Thread t = new Thread(runner, "Code Executer");
        t.start();
    }
    
  2. Manually repaint the progress bar. I did it always with bar.repaint(); but I'm wondering if it will work. I though it was that method. If that doesn't work, try: bar.update(bar.getGraphics());.

Share:
13,847
Hoome
Author by

Hoome

Updated on July 01, 2022

Comments

  • Hoome
    Hoome almost 2 years

    I have strange problem. I set a JProgressBar:

    private JProgressBar progressBar;
    
    public void foo()
    {
        ...
        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);
        ...
        contentPane.add(progressBar);
        ...
    }
    

    But it changes only when I put setValue function it in some places in code, not everywhere:

    public void foo2()
    {
        progressBar.setValue(100); //working
        if(...)
        {
            System.out.println("These instructions are executing"); //working
            progressBar.setValue(0);                                //not working
        }                             
    }
    

    So, what am I doing wrong? Why the second instruction doesn't work?

  • Hoome
    Hoome about 13 years
    Thx. I tried your first solution but I am getting error from NetBeans - "<anonymouse ClassName$1> is not abstract and does not override abstract method run() in java.lang.Runnable"