I am trying to add a progress bar. everything works and i don’t get any error. But the progress bar goes from 0% to 100% without even going through the values between it (I mean it’s too fast, and the users are unable to see the progress bar blocks filling in)
pr = new JProgressBar();
pr(0);
pr(true);
..
public void iterate(){
while (i<=20000){
pr.setValue(i);
i=i+1000;
try{
Thread.sleep(150);
}catch (Exception e){
e.printStackTrace();
}
}
}
When i button is clicked i call the iterate() method, and i expect it to update the progress bar progressively. instead it pauses for a while and then displays a full progress bar.
How can i solve this ?
2.) I don’t like the default blue color of the progress bar tabs. I need to change the color. I tried pr.setForeground(Color.GRAY); But it didn’t work.
pr.setBackground(Color.RED);
The problem is, you’re trying to update the progress within the context of the Event Dispatching Thread.
This basically means that while you are in you loop, the EDT is unable to process any paint request you are making.
What you need to do is some how offload the work to a separate thread and update the progress bar as needed. The problem with this, is you should never update the UI from any thread other then the EDT.
But don’t despair, you have a number of options, the best is using a Swing Worker
Updated with example