要在后台运行一系列操作并报告进度,请使用摇摆工人.
The background
方法进行后台处理。
使用publish
发布定期状态更新的方法。
覆盖process
处理更新的方法(process
始终在 EDT 上执行)。
progressBar = new JProgressBar();
sw = new SwingWorker<Boolean,Integer>() {
protected Boolean doInBackground() throws Exception {
// If any of the operations fail, return false to notify done()
// Do thing 1
publish(25); // 25% done
// Do thing 2
publish(50); // 50% done
// Do thing 3
publish(75); // 75% done
// Do thing 4
return true;
}
protected void process(List<Integer> chunks) {
for (Integer i : chunks)
progressBar.setValue(i);
}
protected void done() {
try {
boolean b = get();
if (b)
progressBar.setValue(100); // 100% done
else
// Notify the user processing failed
}
catch (InterruptedException ex) {
// Notify the user processing was interrupted
}
catch (ExecutionException ex) {
// Notify the user processing raised an exception
}
}
};
附录:
这可以扩展到多个任务,只需要改变设置进度条的方式即可。我想到的是:
有一组完成计数器,每个任务一个。
int[] completions = new int[numTasks];
Arrays.fill(completions,0);
启动SwingWorkers,每个都传递一个索引号。这process
or done
方法然后调用类似的方法来更新整体进度条。
void update(int index, int percComplete) {
completions[index] = percComplete;
int total = 0;
for(int comp: completions)
total += comp/numTasks;
overallPB.setValue(total);
}
(可选)为每个任务显示一个 JProgressBar。
附录2:
如果任务的完成时间不同(例如,缓存命中与缓存未命中),您可能需要调查进度监视器。这是一个进度对话框,仅当任务花费超过一定时间(可配置,默认 500 毫秒)时才会出现。