Should i use SwingUtilities.invokeLater() inside of SwingWorker.doInBackground()?
Asked Answered
K

1

5

The common way to interact with EDT from swing worker is useing get() method. But i have a long task and code like this:

public Void doInBackground() {
    for(Object o : objects) {
         doSomething();
         MyGlobalGUIConsole.addMessage("Done for " + o);
    }
}

In most tutotials is recommended to use return values to get something back from SwingWorker to EDT, but can i just:

public Void doInBackground() {
    for(Object o : objects) {
        doSomething();
        SwingUtilities.invokeLater(new Runnable() {        
            @Override                                      
            public void run() {                            
                MyGlobalGUIConsole.addMessage("Done for " + o);
            }                                              
        });                                                
    }
}
Kenya answered 10/8, 2012 at 8:2 Comment(0)
B
9

You can, but the SwingWorker has methods designed to report progress of a background task: you call publish() from doInBackground() to publish progress, and you override process() (which is called in the EDT) in order to display the progress. So the above code could be rewritten as:

public Void doInBackground() {
    for(Object o : objects) {
        doSomething();
        publish("Done for " + o);                           
    }                                             
}

@Override
protected void process(List<String> messages) {
    for (String message : messages) {
        MyGlobalGUIConsole.addMessage(message);
    }
}
Blueprint answered 10/8, 2012 at 8:11 Comment(1)
@Kenya usage of invokeLater in the SwingWorker is wrong concept, is about wrapping contents from MyGlobalGUIConsole.addMessage() to the invokerLater(), not in the SwingWorker, because process() could be notified EDT properlyColucci

© 2022 - 2024 — McMap. All rights reserved.