我正在尝试使用SwingWorker执行一个耗时的任务,并用结果更新JLabel:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new SwingWorker<String, Void>() {
@Override
protected String doInBackground() throws Exception {
return doCalculation();
}
protected void done() {
try {
label.setText(get());
} catch (InterruptedException e) {
System.out.println("thread was interrupted");
} catch (ExecutionException e) {
System.out.println("there was an ExecutionException");
}
}
}.execute();
}
});
我可以无限制地点击按钮,Gui会保持响应,直到两个线程完成后Gui会冻结。如果我一次只运行一个线程,这个问题仍然存在。
如果有人能指出我是否不正确地使用了SwingWorker,或者是否存在其他我不知道的问题,我将非常感激。谢谢你的时间。 Ian
编辑: doCalculation()只是一个耗时的过程。
private String doCalculation() {
for (int i = 0; i < 10000000; i++) {
Math.pow(3.14, i);
}
return threads++ + "";
}
doCalculation();
方法中发生了什么。您能够发布这段代码吗? - Hovercraft Full Of Eels