Question

I am using a SwingWorker to execute something in the background. During the execution I have a condition where I need to ask the user something by throwing up a JoptionPane.showOptionDialog(). I don't want to do this in my model class and dont want to do this when SwingWorker.doInBackground is executing.

I am sure many people have faced this.

So I have to return back from the call to doInBackground and then ask for the user input in done(). I then need to start another SwingWorker and execute a doInBackground() from the done method?

Is there another neater/simpler way of doing this?

Update (for mkorbel's question)

The class design is like this:

public class OptionInSwingWorker {

    public static void main(String[] args) {
        JFrame frame=new JFrame();
        JButton test = new JButton("Test");
        frame.add(test);

        test.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new SwingWorker<Void,Void>(){
                    @Override
                    protected Void doInBackground() throws Exception {
                        // check for a value in the database

                        // if value is something.. throw up an OptionPane
                        // and ask the user a question..
                        // then do something...
                        return null; 
                    }


                    @Override
                    protected void done() {
                        // open some other dialog
                    }
                }.execute();
            }
        });

    }
}
Was it helpful?

Solution

Make a SwingUtilities.invokeLater call that does a prompt and returns the result back to the SwingWorker. If possible have the SwingWorker move on, otherwise just have it loop and wait while it checks for a response.

This will allow you not have to return and start a new SwingWorker later. Although, depending on what you are doing, starting a new SwingerWorker might actually be cleaner and clearer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top