8

I'm currently working on a project that's getting more complex than I thought it would be originally. What I'm aiming to do right now is show a message dialog without halting the execution of the main thread in the program. Right now, I'm using:

JOptionPane.showMessageDialog(null, message, "Received Message", JOptionPane.INFORMATION_MESSAGE);

But this pauses everything else in the main thread so it won't show multiple dialogs at a time, just on after the other. Could this m=be as simple as creating a new JFrame instead of using the JOptionPane?

Brandon
  • 4,486
  • 8
  • 33
  • 39

3 Answers3

12

According to the docs:

JOptionPane creates JDialogs that are modal. To create a non-modal Dialog, you must use the JDialog class directly.

The link above shows some examples of creating dialog boxes.


One other option is to start the JOptionPane in its own thread something like this:

  Thread t = new Thread(new Runnable(){
        public void run(){
            JOptionPane.showMessageDialog(null, "Hello");
        }
    });
  t.start();

That way the main thread of your program continues even though the modal dialog is up.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
  • OP: Be careful of the modality of the dialogs created by JOptionPane as well though, if you're popping up multiple dialogs then do you really want them to be modal? – iainmcgin Mar 26 '11 at 11:07
  • Thanks iainmcgin. I really didn't think this through. Instead of using "JOptionPane.showMessageDialog" I just created a new JFrame that displayed the message. – Brandon Mar 26 '11 at 22:14
  • Be careful. http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice – user2228462 May 25 '13 at 13:41
  • Firing a new thread did the trick. Seems to be the way to go. Thanks. – Ian Newland Apr 27 '17 at 02:23
0

try this one:

  EventQueue.invokeLater(new Runnable(){
                        @Override
                        public void run() {
                     JOptionPane op = new JOptionPane("Hi..",JOptionPane.INFORMATION_MESSAGE);
                     JDialog dialog = op.createDialog("Break");
                     dialog.setAlwaysOnTop(true);
                     dialog.setModal(true);
                     dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);      
                     dialog.setVisible(true);
                        }
                    });
kelvz
  • 87
  • 1
  • 2
  • 13
0

You could just start a separate Runnable to display the dialog and handle the response.

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189