ProgressBar does not change its value in Java

I have a strange problem. I installed JProgressBar:

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

But it only changes when I set the setValue function in some places in the code, and 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 does the second instruction not work?

+4
source share
2 answers

The progress bar value is indeed updated. But it is not just on the screen. Often we use progress indicators in cycles. But, although you are in a loop, which you are probably invoked by pressing a button , it is not painted. What for? Because you called it by pressing a button. When you click a button, all the code that you made for that button is executed by AWTEventThread . This is the same thread that tracks all Swing components and checks to see if they should be repainted. This is the thread that makes your JFrame come to life. When you hover the button and the color changes a bit, this will be done using AWTEventThread .

So, while you are working in a loop, AWTEventThread can no longer refresh the screen.

This means that there are two solutions:

  • (Recommend) You must create a separate thread that runs the loop. This means that 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(); } 
  • Manually redraw the progress bar. I always did this with bar.repaint(); but I wonder if this will work. I though it was this method. If this does not work, try: bar.update(bar.getGraphics()); .

+15
source

Despite the fact that this question was answered, I found another way that really worked for me. I used swing worker and using propertyChange (null) to update the progress bar was the easiest solution.

Just wanted to offer this alternative.

-1
source

All Articles