Search code examples
javaswingswingworker

How to stop a called static method in doInBackground() of SwingWorker


I have a SwingWorker called Task1,

class Task1 extends SwingWorker<Void, Void> {
        @Override
        public void doInBackground() {
            String[] args = {};
            try {
                FeatureSetBuilder.main(args); //<---It is a static method


            } catch (Exception e1) {
                e1.printStackTrace();
            }

            return null;
        }
        public void done() {

            UISettings.FP_GENERATOR_DIALOG_2.cancelButton.setEnabled(true);
            loadingDialog.progressBar.setIndeterminate(false);
            loadingDialog.setVisible(false);
        }
    }

And I have a button that will execute Task1,

         public void actionPerformed(ActionEvent e) {
                System.out.println("FeatureSetBuilder - Start");
                String[] args = {};
                try {
                    task1 = new Task1();
                    task1.execute();
                    loadingDialog.popOut(task1);
                    task1.cancel(true);



                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                System.out.println("FeatureSetBuilder - Finished");

            }

When I click this botton, a dialog with a progress bar will pop out to indicate that the method FeatureSetBuilder.main(args) is running. When task1 completes, the method done() will then be called and close that dialog.

It works fine.

I want to add a Cancel button to that dialog so the user can terminate task1 whenever he wants.

Here is my Cancel button,

 cancelButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Stop the current SwingWorker");
                    task.cancel(true);
                    setVisible(false);
                }
            });

When I press the the Cancel button, the task 1 seems being terminated as "FeatureSetBuilder - Finished" is printed out. However, the static method FeatureSetBuilder.main(args) is still running.


Solution

  • Your doInBackground method should be periodically checking whether the task has been cancelled. Example from SwingWorker class' javadoc:

    @Override
    public List<Integer> doInBackground() {
        while (! enough && ! isCancelled()) {
                number = nextPrimeNumber();
                publish(number);
                setProgress(100 * numbers.size() / numbersToFind);
            }
        }
        return numbers;
    }
    

    I really recommend that you read the javadocs of all classes/methods in SwingWorker and related classes. EventDispatchThread related problems can be very tricky.