Showing “JOptionPane.showMessageDialog” without stopping flow of execution

孤街浪徒 提交于 2019-12-04 21:10:09

问题


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?


回答1:


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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/5440226/showing-joptionpane-showmessagedialog-without-stopping-flow-of-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!