1

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

Community
  • 1
  • 1
Josh
  • 818
  • 2
  • 16
  • 27

2 Answers2

2

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)

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • thanks for that. using a swing timer can i force it to only exit the method after the timer as stopped running? – Josh Nov 24 '11 at 18:21
  • @Josh I think that yes, but (sorry for that) as I see your thread, please post your idea/question about Timer translated to the Java code, then most of readers can answering ...., just edit your question and add new code, based for example javax.swing.Timer with SwingWorker http://stackoverflow.com/q/6186188/714968 – mKorbel Nov 24 '11 at 18:26
1

If you want to block, then don't use a swing worker, just do

changeNodeColor(node, Color.WHITE);
Thread.sleep(500);
changeNodeColor(node, origColor);
Thread.sleep(500);

on the EDT. SwingWorker's whole purpose is to not block the EDT.

If you just want to change the color of a component at certain intervals (i.e. flash the component) then a javax.swing.Timer might be more appropriate.

Qwerky
  • 18,217
  • 6
  • 44
  • 80
  • 1
    I forgot to notice your answer, never really, never to suggest block EDT as an answer for newbee, this way could be road to the hell without deepest knowledges about Swing's EDT, please remove these words and code – mKorbel Nov 24 '11 at 17:18