Search code examples
javasleeppollingeventqueueinvokeandwait

Waiting for invokeLater() to be called


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;
    }
}

Solution

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