【发布时间】:2018-02-12 09:35:15
【问题描述】:
我正在为一个计算密集型程序的 GUI 工作,并且需要一些时间才能完成计算。我想在 GUI 上显示和更新处理时间,以供参考和向用户指示程序正在运行。我创建了一个工作人员来处理单独线程上的处理时间,如下所示:
public class Worker extends SwingWorker<String, String>{
JLabel label;
boolean run;
public Worker(JLabel label)
{
this.label = label;
this.run = true;
}
@Override
protected String doInBackground() throws Exception {
//This is what's called in the .execute method
long startTime = System.nanoTime();
while(run)
{
//This sends the results to the .process method
publish(String.valueOf(System.nanoTime() - startTime));
Thread.sleep(100);
}
return null;
}
public void stop()
{
run = false;
}
@Override
protected void process(List<String> item) {
double seconds = Long.parseLong(item.get(item.size()-1))/1000000000.0;
String secs = String.format("%.2f", seconds);
//This updates the UI
label.setText("Processing Time: " + secs + " secs");
label.repaint();
}
}
我将 JLabel 传递给显示处理时间的 Worker。以下代码创建了 Worker 并执行了一个执行主要计算的 runnable。
Worker worker = new Worker(jLabelProcessTime);
worker.execute();
//Check for results truncation
boolean truncate = !jCheckBoxTruncate.isSelected();
long startTime = System.nanoTime();
String[] args = {fileName};
//run solution and draw graph
SpeciesSelection specSel = new SpeciesSelection(args, truncate);
Thread t = new Thread(specSel);
t.start();
t.join();
ArrayList<Double> result = specSel.getResult();
drawGraph(result);
worker.stop();
我的问题是,直到计算完成后,GUI 上的处理时间才会更新。我想我已经很接近了,因为没有 't.join();'计时器更新正常,但处理永远不会完成。我真的很感激能帮助您找出问题所在。
【问题讨论】:
-
在 Swing 中的一个基本规则是使用
SwingUtilities.invokeLater(Runnable)以便在您在 不同 线程中进行计算之后将 GUI 更新任务添加到 Swing 的队列中而不是图形用户界面线程。 Swing 的引擎将负责线程安全地应用您的更新 -
你在哪里
t.join();?看起来您是在阻止它的 UI 线程上执行此操作... -
代码的下半部分在一个action执行的事件代码块中。
标签: java multithreading swing user-interface