因此,我有一个扩展swingworker的类,并在磁盘上的所有文件中搜索字符串。在此类中,doInBackground调用fileFindNoCase()并设置一个等于结果的字符串。在fileFindNoCase()中,我检查isCancelled()是否为true,然后立即让它返回空字符串。但是,当我执行SwingWorker并尝试取消它(通过sw.cancel(true))时,swingworker的done()方法中的isCancelled()将返回true,但doInBackground()方法中的isCancelled()仍返回假。为什么会这样呢?有想法该怎么解决这个吗?任何朝着正确方向的推动都值得赞赏。另一个可以缓解我的问题的问题,还有另一种方法,当我按下“取消”按钮后,通知代码的doInBackground()部分,然后按下“取消并停止”
在这里我用按钮称呼它
fileFindNoCaseWorker sw = new fileFindNoCaseWorker(fi, "must", true, true, true, true, true, ta_p1, progressBar_p1, canc);
if(actionEvent.getActionCommand().equals("Find")) {
sw.execute();
} else if(actionEvent.getActionCommand().equals("Cancel")) {
sw.cancel(true);
logger.info("cancel was hit");
}
这是SwingWorker类的相关部分
@Override
protected String doInBackground() throws Exception {
result = fileFindNoCase(file, word, html, txt, cfg, java, css);
return result;
}
public String fileFindNoCase(File file, String word, Boolean html, Boolean txt, Boolean cfg, Boolean java, Boolean css) throws Exception {
String results = "";
File[] totalFiles = file.listFiles();
if (totalFiles != null) {
for (int i = 0; i < totalFiles.length; i++) {
if (totalFiles[i].isDirectory()) {
if (isCancelled()) {
return "";
}
fileFindNoCase(totalFiles[i], word, html, txt, cfg, java, css);
} else if (totalFiles[i].isFile()) {
System.out.println("got here");
if (totalFiles[i].toString().endsWith(".txt") && txt == true) {
if (isCancelled()) {
System.out.println("cancelled was true");
return "";
}
System.out.println("is cancelled is " + isCancelled());
results = results + ds.findNoCase(totalFiles[i], word);
} else if (totalFiles[i].toString().endsWith(".html") && html == true) {
if (isCancelled()) {
return "";
}
results = results + ds.findNoCase(totalFiles[i], word);
} else if (totalFiles[i].toString().endsWith(".cfg") && cfg == true) {
if (isCancelled()) {
return "";
}
results = results + ds.findNoCase(totalFiles[i], word);
} else if (totalFiles[i].toString().endsWith(".java") && java == true) {
if (isCancelled()) {
return "";
}
results = results + ds.findNoCase(totalFiles[i], word);
} else if (totalFiles[i].toString().endsWith(".css") && css == true) {
if (isCancelled()) {
return "";
}
results = results + ds.findNoCase(totalFiles[i], word);
}
}
}
}
return results;
}
@Override
public void done() {
try {
//result = get();
if (isCancelled()) {
ta.setText("was canceled");
} else {
ta.setText(get());
pbar.setVisible(false);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}