SwingWorker isCancelled () возвращает разные значения - PullRequest
0 голосов
/ 07 октября 2018

Итак, у меня есть класс, который расширяет SwingWorker и ищет строку во всех файлах на моем диске.В этом классе doInBackground вызывает fileFindNoCase () и устанавливает строку, равную результатам.В fileFindNoCase () я проверяю, является ли isCancelled () истиной, а затем немедленно возвращает пустую строку.Однако, когда я выполняю свой SwingWorker и пытаюсь отменить его (через sw.cancel (true)), isCancelled () в методе done () объекта swingworker вернет true, но isCancelled () в методе doInBackground () по-прежнему возвращаетложный.Почему это происходит?Любые идеи о том, как это исправить?Любой толчок в правильном направлении очень ценится.Другой вопрос, который может облегчить мою проблему, , есть ли другой способ, когда я нажимаю кнопку отмены, уведомляю часть кода 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();
    }


}
...