Search code examples
javamultithreadingswingswingworker

Is there a way to block the main thread until a swingworker is done?


Possible Duplicate:
How do I wait for a SwingWorker's doInBackground() method?

I've read that its really bad practice to do this but I think its the best way for me to achieve my goal... Is there a way to block the main thread until the swing worker has finished in the following example?

public void flashNode(Node node, int noOfFlashes) {
    GraphUpdater updater = new GraphUpdater(node, noOfFlashes);
    updater.execute();
}

and the SwingWorker class

    public class GraphUpdater extends SwingWorker<Integer, Integer> {
    Node node;
    int noOfFlashes;

    public GraphUpdater(Node n, int noFlashes) {
        node = n;
        noOfFlashes = noFlashes;
    }

    @Override
    protected Integer doInBackground() throws Exception {
        Color origColor = node.getColor();
        for (int i=0; i<noOfFlashes; i++) {
            changeNodeColor(node, Color.WHITE);
            Thread.sleep(500);
            changeNodeColor(node, origColor);
            Thread.sleep(500);
        }

        return 1;
    }

}

Thanks in advance


Solution

  • as I mentioned, never use Thread#sleep(int) during Swing EDT, GUI simple freeze until Thread#sleep(int) ends, more in the Concurency in Swing, example about freeze here

    you have three (maybe four) options how to update GUI on some period or to delay per time some execution(s)

    put all together here (plus java.util.Timer with executions wrapped into invokeLater)