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?
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 theAWTEventThread.So, while you are working in the loop, the AWTEventThread can’t update the screen anymore.
This means there are two solutions:
(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(...);)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());.