java 在不停止执行流程的情况下显示“JOptionPane.showMessageDialog”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5440226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Showing "JOptionPane.showMessageDialog" without stopping flow of execution
提问by Brandon
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?
但这会暂停主线程中的所有其他内容,因此它不会一次显示多个对话框,而是一个接一个地显示。这个 m= 可以像创建一个新的 JFrame 而不是使用 JOptionPane 一样简单吗?
回答by Vincent Ramdhanie
According to the docs:
根据文档:
JOptionPane creates JDialogs that are modal. To create a non-modal Dialog, you must use the JDialog class directly.
JOptionPane 创建模态的 JDialog。要创建非模态对话框,您必须直接使用 JDialog 类。
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:
另一种选择是在自己的线程中启动 JOptionPane,如下所示:
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.
这样,即使模式对话框已启动,程序的主线程仍会继续。
回答by Lawrence Dol
You could just start a separate Runnable
to display the dialog and handle the response.
您可以单独启动一个Runnable
来显示对话框并处理响应。
回答by kelvz
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);
}
});