1

I had a problem earlier where I was trying to add objects to my canvas but the SwingUtilities.invokeLater hadn't really done its job yet. I really need to be able to add things reliably to this JPanel but I keep running into this same error. Is there a better alternative to the below code?

private void startNewGame() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            gameFrame = new InvadersGameFrame();
        }
    });
}
Community
  • 1
  • 1
user1695505
  • 265
  • 2
  • 13
  • 2
    As an aside: I entered that answer before carefully reading the question. `invokeLater` has always worked reliably for me. The problem is elsewhere. For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). – Andrew Thompson Apr 22 '14 at 02:37
  • I think that the invocations of `SwingUtilities.invokeLater` are queued. That means that if you call `SwingUtilities.invokeLater` to add the object to the jpanel before calling it to add `new InvadersGameFrame();` the first invocation should be executed before the second one. – Totò Apr 22 '14 at 02:38
  • 1
    This smells strongly like an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Hovercraft Full Of Eels Apr 22 '14 at 02:49

1 Answers1

4

See SwingUtilities.invokeAndWait(Runnable) which:

Causes doRun.run() to be executed synchronously on the AWT event dispatching thread. This call blocks until all pending AWT events have been processed and (then) doRun.run() returns. This method should be used when an application thread needs to update the GUI.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433