0

As said on my title, my showConfirmDialog never waits for a "Yes" or "No" button press whenever I call it.

Originally I encountered a bug that involved me getting blank JOptionPanes, so now I'm using the invokeLater method. I'm not too familiar with the concept so I apologize beforehand.

public int firstGame()
{

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            yOrN = JOptionPane.showConfirmDialog(null,
                    "Are you ready to play?\n", "Play?", JOptionPane.YES_NO_OPTION);
        }
    });
    return yOrN;
    // will return 0 if yes and 1 if no.

}

Before using invokeLater, it was working fine (except for the blank JOptionPanes). Does this method run another thread? Howcome my showInputDialog waits for an input and not this one?

Zoyd
  • 3,449
  • 1
  • 18
  • 27
kir
  • 581
  • 1
  • 6
  • 22

1 Answers1

2

SwingUtilities.invokeLater does just that, it places the Runnable onto the event queue to be run later, meaning that once you called it, your return statement is executed almost immediately after it and some time in the future, the JOptionPane will be displayed.

Requests of this type are placed on the event queue and are process by the Event Dispatching Thread

Have a look at How to pass results from EDT back to a different thread? for a possible solution...

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thank you for the neat explanation! And crap the solution is way out of the scope of what I learned so far. I'll take a look into it. Thanks again! – kir Oct 10 '13 at 06:17
  • I've being doing this for 14 years and `Future` still scares me :P...neat solution though – MadProgrammer Oct 10 '13 at 06:17
  • @MadProgrammer +1 for isEventDispatch... , in other hand talking about sceleton and its notifiers are wrong designed, no idea how to create code example caused by OPs ... – mKorbel Oct 10 '13 at 06:25
  • @MadProgrammer: I'm sorry if this is quite the late question but you think I can use invokeLaterAndWait instead? My application only uses `JOptionPane`s and nothing else, as everything else is in the console. – kir Oct 10 '13 at 07:33
  • So long as you're not running within the Event Dispatching Thread, then yes you could do this. You should make a check using `EventQueue.isEventDispatchingThread` before using `invokeAndWait`, it throws an exception if you try and do this in the EDT – MadProgrammer Oct 10 '13 at 07:35