Waiting for invokeLater() to be called

1.4k Views Asked by At

Is there a more elegant way to do what I'm doing below? That is, is there a more elegant way than polling and sleeping, polling and sleeping, and so on to know when a Runnable.run() method has been called via invokeLater()?

private int myMethod() {
    final WaitForEventQueue waitForQueue = new WaitForEventQueue();
    EventQueue.invokeLater(waitForQueue);
    while (!waitForQueue.done) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException ignore) {
        }
    }

    return 0;
}

private class WaitForEventQueue implements Runnable {
    private boolean done;

    public void run() {
        // Let all Swing text stuff finish.
        done = true;
    }
}
3

There are 3 best solutions below

3
On BEST ANSWER

If you want to wait, why not call invokeAndWait rather than implement it yourself?

1
On

Instead of waiting for the thread to finish, why not just have the UI display a spinner or something, and have the thread call an event when it is done.

0
On

A better way would be to use a FutureTask (which implements Runnable and Future) and override its done() event to do something when finished.

Also, start this as a separate thread (or use an Executor) if it's not doing GUI manipulation, rather than using the AWT EventQueue.