1

I've just learned about executing swing background tasks and I'm starting to experiment with it but I'm having a little trouble with implementation. My code retrieves an image and returns a result (an integer) that indicates whether the image retrieval was successful result = 0 or unsuccessful result = -1. Here is my problem, I am retrieving the result too soon. I can see statements in the createImage method in the code below executing after the result is read in the done() method. I guess I thought that the done method would not execute until the createImage was done. Here is my code below:

new SwingWorker<int[], Void>() {
int result = -1;
@Override
protected int[] doInBackground() throws Exception {
 // TODO Auto-generated method stub
return createImage();  //returns an integer array of size one indicating the result
                    }

protected void done() {
try {
result = get()[0];  //this result is being read before createImage is done  
                        //executing.  Why?
thisApplet.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
tree.setEnabled(true);
if (result == -1){
    tree.setSelectionPath(null);
     return;
}
   } catch (InterruptedException e) {                                 
         e.printStackTrace();
    } catch (ExecutionException e) {                          
            e.printStackTrace();
    }
      }
}.execute();

1 Answer 1

2

The done method will not execute until the doInBackground method is completed. So there must be something else going on here. I would guess that you might be calling done and doInBackground instead of run()? If not, try to find the issue by creating an SSCCE.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. A stupid programming error. When I fixed it everything worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.