如何立即停止SwingWorker.doInBackground进程?

时间:2017-01-10 01:38:51

标签: java swing swingworker

根据Oracle docs SwingWorker.doInBackground,不包含任何可能引发InterruptedException"的代码。 Dunno如果我对我的理解是正确的,但我注意到取消doInBackground进程打印出InterruptedException,所以即使遇到Exception它也会继续?那么我们如何立即取消并停止该过程呢?

所以我在取消return STATUS;时尝试了PROCESS.destroyForcibly()但仍在继续。我在return之前尝试了import ... public class Test { private BackgroundProcess BG_PROCESS; private JFileChooser FILE_CHOOSER; private JProgressBar PROGRESS_BAR; public Test() { initComponents(); } ... private class BackgroundProcess extends SwingWorker<Integer, String> { private int STATUS; @Override protected Integer doInBackground() throws Exception { File[] SELECTED_FILES = FILE_CHOOSER.getSelectedFiles(); for (int i = 0; i < SELECTED_FILES.length; i++) { String file = SELECTED_FILES[i].getAbsolutePath(); String name = SELECTED_FILES[i].getName(); String[] command = {"javac", "" +file+ ""}; try { ProcessBuilder PROCESS_BUILDER = new ProcessBuilder(command); Process PROCESS = PROCESS_BUILDER.start(); if (!isCancelled()) { STATUS = PROCESS.waitFor(); if (STATUS == 0) { TEXTAREA.append(name+ "Successfully compiled."); } else { TEXTAREA.append(name+ "Failed. (not compiled)"); } } else { TEXTAREA.append("Compilation cancelled."); return STATUS; } PROCESS.destroy(); } catch (IOException | InterruptedException ex) { ex.printStackTrace(System.err); } } return STATUS; } } public static void main(String[] args) { new Test(); } } ,但仍然相同。一旦取消,如何立即停止?

JButton START = new JButton("Start");
START.addActionListener(new ActionListener() {
    @Override
    ...

    BG_PROCESS = new BackgroundProcess();
    BG_PROCESS.execute();
    PROGRESS_BAR.setIndeterminate(true);
});

启动BackgroundProcess

JButton CANCEL = new JButton("Cancel");
CANCEL.addActionListener(new ActionListener() {
    @Override
    ...

    BG_PROCESS.cancel(true);
    PROGRESS_BAR.setIndeterminate(false);
});

取消BackgroundProcess

{{1}}

0 个答案:

没有答案