我正试图找出如何在按下按钮时停止运行SwingWorker线程.我一直在四处寻找,我在解决如何做到这一点时遇到了一些麻烦.目前这就是我所拥有的:
new MySwingWorkerClass(args).execute();
Run Code Online (Sandbox Code Playgroud)
我正在创建一个按钮,我想用它来停止线程:
button = new JButton("Stop");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Stop the swing worker thread
}
});
Run Code Online (Sandbox Code Playgroud)
我已经环顾四周寻找答案,到目前为止我已经设法找到了取消方法.我不明白如何使用它来阻止我的摇摆工作者.我尝试了以下但它不起作用:
SwingWorker.cancel(true);
Run Code Online (Sandbox Code Playgroud) Javadoc的done()方法SwingWorker:
在doInBackground方法完成后在Event Dispatch Thread上执行.
我已经找到了在取消工人的情况下不是这样的线索.
Done在每种情况下都会被调用(正常终止或取消),但是当cancelled它没有排入 EDT时,就像正常终止时那样.
done在SwingWorker取消a的情况下调用时是否有一些更精确的分析?
澄清:这个问题不是关于如何做到cancel的SwingWorker.这里假设SwingWorker以正确的方式取消.
而且当它们应该完成时,它不是关于线程仍在工作.
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
Queue queue=new Queue();
int target=Integer.parseInt(Target.getText());
String path=Path.getText();
final Producer p=new Producer(queue, target);
Consumer c=new Consumer(queue);
p.start();
c.start();
while(p.finish !=true)
{
Runnable r = new Runnable() {
public void run() {
ProgressPrecent.setValue(Producer.ProgressPercent);
}
};
if(EventQueue.isDispatchThread()) {
r.run();
}
else {
EventQueue.invokeLater(r);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有两个具有共享队列的类.其中一个是Producer,它生成直到一个目标,另一个消耗这些元素.所有两个都扩展了Thread.我想向用户显示进度百分比,但它会冻结我的GUI,所以我该怎么办?
我使用swingworkers来提取zipfile,并将提取的prosecc附加到GUI中的textArea.它只从压缩文件中提取一个项目,并且没有在textArea中显示任何内容.
有谁能建议任何解决方案?
public class UnzipWorkers extends SwingWorker<String,Void> {
private WebTextArea statusTextArea;
private File archive,outputDir;
public UnzipWorkers(WebTextArea statusTextArea,File archive,File outputDir) {
this.archive=archive;
this.outputDir=outputDir;
this.statusTextArea = statusTextArea;
}
@Override
protected String doInBackground() throws Exception {
statusTextArea.append(String.valueOf(System.currentTimeMillis()));
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, outputDir);
}
} catch (Exception e) {
OeExceptionDialog.show(e);
}
return "Extracted successfully: " + archive.getName() + "\n";
}
@Override
protected void done() {
super.done(); …Run Code Online (Sandbox Code Playgroud)