How to stop SwingWorker.doInBackground process immediately?

393 views Asked by At

According to Oracle docs SwingWorker.doInBackground does not include any code that might throw InterruptedException". Dunno if I'm right about what I understand, but I noticed that cancelling the doInBackground process prints out the InterruptedException so it'll continue even if an Exception is encountered? Then how can we cancel and stop the process immediately?

So I tried return STATUS; when it is cancelled but still continues. I also tried PROCESS.destroyForcibly() before return but still the same. How to stop it immediately once cancelled?

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();
    }
}

Start BackgroundProcess

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

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

Cancel BackgroundProcess

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

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

There are 0 answers