I want to change a progress bar use SetValue(int),but it doesn’t work,it always change directly from 0 to 100 when progress finish.I try to create a new thread to invoke “setValue(int)”,instead of invoking form UI thread,but it’s still not worked.
my code:
public class UpdateProgressBar extends Thread{
public UpdateProgressBar(javax.swing.JProgressBar progressBar){
this.progressBar = progressBar;
}
public void update(){
for(int i = 1; i <= 100; i++){
progressBar.setValue(i);
try {
sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(UpdateProgressBar.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private javax.swing.JProgressBar progressBar;
}
,progressBar is defined in UI thread,then I UpdateProgressBar upb = new UpdateProgressBar(progressBar); in UI thread and invoke it’s update wayupb.update();did I make some mistake?
Although you have declared
UpdateProgressBarto extendThreadyou are not actually running it as a separate thread. You need to callstart()to make the new thread actually run. If you callupb.update()from the event dispatch thread then you are executing that method on the event dispatch thread.You want this in your client code:
and change your
UpdateProgressBarclass to this:You need to have the
SwingUtilities.invokeLaterbecause Swing components are not thread-safe. You also need the nastyfinal int j = ibecause of Java’s less-than-brilliant handling of closures. Putting your code into therunmethod means it will be executed when you callThread.start().