gpt4 book ai didi

java - 停止/取消 SwingWorker 线程?

转载 作者:IT老高 更新时间:2023-10-28 21:17:45 25 4
gpt4 key购买 nike

我试图找出当我按下按钮时如何阻止 SwingWorker 线程运行。我一直在环顾四周,但在弄清楚如何做到这一点时遇到了一些麻烦。目前这就是我所拥有的:

new MySwingWorkerClass(args).execute();

然后我创建了一个按钮,我想用它来停止线程:

button = new JButton("Stop");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Stop the swing worker thread
}
});

我已经四处寻找答案,到目前为止我已经设法找到取消方法。我不明白如何用它来阻止我的 Swing worker 。我尝试了以下方法,但没有成功:

SwingWorker.cancel(true);

最佳答案

您需要为您的 SwingWorker 保留一个引用,然后使用该引用来取消工作线程。

MySwingWorker myWorker = new MySwingWorkerClass(args).execute();

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Stop the swing worker thread
myWorker.cancel(true);
}
});

这是一个完整的例子:

enter image description here

public class WorkerDemo extends JFrame {
private boolean isStarted = false;
private JLabel counterLabel = new JLabel("Not started");
private Worker worker = new Worker();
private JButton startButton = new JButton(new AbstractAction("Start") {

@Override
public void actionPerformed(ActionEvent arg0) {
if(!isStarted) {
worker.execute();
isStarted = false;
}
}

});
private JButton stopButton = new JButton(new AbstractAction("Stop") {

@Override
public void actionPerformed(ActionEvent arg0) {
worker.cancel(true);
}

});

public WorkerDemo() {

add(startButton, BorderLayout.WEST);
add(counterLabel, BorderLayout.CENTER);
add(stopButton, BorderLayout.EAST);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

class Worker extends SwingWorker<Void, Integer> {

int counter = 0;

@Override
protected Void doInBackground() throws Exception {
while(true) {
counter++;
publish(counter);
Thread.sleep(60);
}
}

@Override
protected void process(List<Integer> chunk) {

// get last result
Integer counterChunk = chunk.get(chunk.size()-1);

counterLabel.setText(counterChunk.toString());
}

}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new WorkerDemo();
}

});
}

}

关于java - 停止/取消 SwingWorker 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8083768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com