Search code examples
javaswingswingworker

How to chain multiple SwingWorkers


I've got a big background task with some intermediate points where a user input is required.

E.g. buttonLoad_actionPerformed --> load, verify validity --> if outdated, ask user whether to update. If yes --> update, if no --> stop.

For now, I've coded this like this:

// load worker
SwingWorker<Status,Object> swLoad=new SwingWorker<> () {
    Validity doInBackGround() {
        return load(file);
    }

    void done() {
        Validity validity=get();

        switch (validity) {
            case UPTODATE:
                return;
            case OUTDATED:
                int res=JOptionPane.showConfirmDialog("File obsolete. Do you want to update it ?");
                if (res != JOptionPane.YES_OPTION) 
                    return;
                    
                // update worker
                SwingWorker<Boolean,Object> swUpdate = new SwingWorker<>() {
                    Boolean doInBackGround() {
                        return update();
                    }

                    void done() {
                        Boolean success=get();
                        if (!success) ....
                    }
                };
                
                swUpdate.execute();
        }    
    }
};

swLoad.execute();

However this can be become pretty unreadable if multiple steps are required.

What's the best approach for chaining conditional/optional SwingWorkers ?


Solution

  • I don't understand why you're doing anything in your done method.

    Validity doInBackGround() {
        Validity validity = load(file);
        switch (validity) {
            case UPTODATE:
                return validity;
            case OUTDATED:
                int res= confirmOnEdt();
                if (res == JOptionPane.YES_OPTION) {
                    Boolean success = update();
                    //check the update and respond.
                }
        }
        return validity;
    }
    
    public int confirmOnEDT() throws InterruptedException{
        int[] container = {0};
        SwingUtilities.invokeAndWait( ()->{
                container[0] = JOptionPane.showConfirmDialog("File obsolete. Do you want to update it ?");
            }
        );
        return container[0];
    }
    

    One SwingWorker for the full set of tasks. The JOptionPane will block your background thread and wait for input. Also, you probably want to different return value than Validity.