【发布时间】:2014-02-09 18:11:22
【问题描述】:
我有一个带有开始和停止按钮的窗口。开始按钮启动算法,停止按钮应该停止它。我使用SwingWorker 在后台运行算法,通常调用worker.cancel(true) 应该停止算法运行。我还有一个标签,可以显示状态,例如如果我按下“Stop”,Labeltext 会变为“stopped”,所以问题不在 Button 的 actionLister 上。
我的代码如下所示:
public class MainWindow extends JFrame implements ActionListener, WindowListener
{
// Some code, like generating JFrame, JButtons and other stuff not affencting the task.
Worker worker = new Worker();
public void actionPerformed(ActionEvent e)
{
boolean isStarted = false;
// Start Button
if (e.getSource() == this.buttonStart)
{
if(!isStarted)
{
System.out.println("start");
labelSuccess.setText("Mapping started!");
this.setEnabled(true);
worker.execute();
isStarted = false;
}
}
// Stop Button
if (e.getSource() == this.buttonStop)
{
labelSuccess.setText("Mapping stopped!");
worker.cancel(true);
}
}
class Worker extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
if(!isCancelled())
{
mapp();
Thread.sleep(60);
if (isCancelled()) {
System.out.println("SwingWorker - isCancelled");
}
}
return null;
}
}
此时,按下停止按钮只会导致标签文本发生变化,但后台的算法仍在运行。现在这困扰了我很长一段时间,我就是无法继续。
非常感谢您的帮助,非常感谢。
edit1:我现在在 actionPerformed 之外生成了一个新的 worker 实例,所以现在每次鼠标点击都不会生成新的 Worker。
【问题讨论】:
-
如果在 mapp() 中有一个循环,你必须在那里处理一个 InterruptedException。我不认为你会来你的“SwingWorker isCancelled”。
-
您正在每个
button click中创建一个worker 实例,请参阅Worker worker = new Worker();它们与您取消的那个与您要取消的那个无关。
标签: java multithreading swing swingworker