这应该可以通过SwingWorker
实现轻松管理。SwingWorker
当您需要“做某事”但又不想在做某事时阻止 GUI 时,s 很有用。当您需要更新 GUI 组件同时通过这些publish()/process()
方法进行其他工作时,该类还为您提供了一个有用的 API,用于与 EDT 进行通信。
以下实现在工作线程上处理您的循环,以便它不会阻塞 EDT(GUI 线程)。调用publish(Integer...)
被中继到 EDT,作为process(List)
您要更新 JProgressBar 的调用,因为与所有 Swing 组件一样,您应该只更新 EDT 上的 JProgressBar。
public class MySwingWorker extends SwingWorker<Void, Integer> {
private final int qtd;
private final JProgressBar progressBar;
public MySwingWorker(JProgressBar progressBar, int qtd){
this.qtd = qtd;
this.progressBar = progressBar;
}
/* This method is called off the EDT so it doesn't block the GUI. */
@Override
protected Void doInBackground() throws Exception {
for(int i = 0; i < qtd; i++) {
/* This sends the arguments to the process(List) method
* so they can be handled on the EDT. */
publish(i + 1);
/* Do your stuff. */
doSomething();
}
return null;
}
/* This method is called on the EDT in response to a
* call to publish(Integer...) */
@Override
protected void process(List<Integer> chunks) {
progressBar.setValue(chunks.get(chunks.size() - 1));
}
}
你可以这样开始
int qtd = ...;
progressBar.setMinimum(0);
progressBar.setMaximum(qtd);
SwingWorker<? ,?> worker = new MySwingWorker(progressBar, qtd);
worker.execute();