2

We have a Swing application with socket communication and other threads. We know we need to use SwingUtilities.invokeLater() to update Swing display from other threads. But how about JOptionPane? do we need to use SwingUtilities.invokeLater() from other threads to launch JOptionPane?

if the answwer is yes, how to use JOptionPane to block the procedure?

if the answer is no, doesn't JOptionPane belong to GUI display?

5YrsLaterDBA
  • 33,370
  • 43
  • 136
  • 210

3 Answers3

3

if the answwer is yes, how to use JOptionPane to block the procedure

The answer is indeed yes. You should access/modify/... all Swing components on the Event Dispatch Thread. So your background thread needs to use some mechanism to call the JOptionPane on the EDT. Using SwingUtilities#invokeLater is an option, but not a blocking one.

Use SwingUtilities#invokeAndWait for the blocking behavior. This method will wait until the runnable is finished before returning.

Robin
  • 36,233
  • 5
  • 47
  • 99
  • +1 I didn't realize the question could be interpreted 2 ways until I read your comment on the question. The OP probably meant it your way. – Nick Rippe Dec 13 '12 at 21:19
2

Yes, you need to use SwingUtilities.invokeLater() to launch the JOptionPane - otherwise the JOptionPane may not be responsive. Since it's a modal container, it should block input to the main container by default. See http://docs.oracle.com/javase/6/docs/api/javax/swing/JOptionPane.html for more details.

Nick Rippe
  • 6,465
  • 14
  • 30
  • I may have misunderstood your question. I was thinking you wanted the JOptionPane to block user input on the parent frame. If you want the JOptionPane to block further execution of a program, you'll need to use Robin's suggestion: SwingUtilities.invokeAndWait() - http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html#invokeAndWait(java.lang.Runnable) – Nick Rippe Dec 13 '12 at 17:50
2

The answer is yes, you have to call swing components only from the EventQueue. Have a look at Is JOptionPane.showMessageDialog thread safe?

Community
  • 1
  • 1
Slauster
  • 99
  • 1