java 获取 JOptionPane 的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1215436/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:40:02  来源:igfitidea点击:

Get the return value of JOptionPane

javajoptionpane

提问by burntsugar

My JOptionPane code is as follows:

我的 JOptionPane 代码如下:

selectedSiteName = JOptionPane.showInputDialog("Enter the name of the new site:");

This renders out an input with a textbox and an OK and Cancel button. I need to detect if Cancel was clicked.

这将呈现一个带有文本框和 OK 和 Cancel 按钮的输入。我需要检测是否单击了取消。

Cheers.

干杯。

回答by Jataro

Check if selectedSiteName == null .
This will be the case if the user clicks Cancel or closes the dialog.

检查是否 selectedSiteName == null 。
如果用户单击取消或关闭对话框,就会出现这种情况。

回答by camickr

Read the JOptionPane API and follow the link to the Swing turorial on "How to Use Dialogs" for a working example.

阅读 JOptionPane API 并按照“如何使用对话框”的 Swing 教程链接获取工作示例。

回答by Nick Gibson

if(selectedSiteName == JOptionPane.CANCEL_OPTION)
{


}

should work.

应该管用。

回答by Jakub Iskerka

JOptionPane extends JComponent.

JOptionPane 扩展了 JComponent。

Methods of JOptionPane
1) .showMessageDialog(); // VOID :-(
2) .showInputDialog(); // return STRING :-)
3) .showConfirmDialog(); // return int :-)
-> and more...

JOptionPane 的方法
1) .showMessageDialog(); // 无效 :-(
2) .showInputDialog(); // 返回字符串 :-)
3) .showConfirmDialog(); // 返回 int :-)
-> 等等...

Example:

例子:

void myMethod() {

        JDialog jd = new JDialog();
        jd.setDefaultCloseOperation(1);

        JOptionPane jop = new JOptionPane();
        int val = jop.showConfirmDialog(jd, "Hello");
        if(val == 0) jop.showMessageDialog(null, "Success", "INFO", jop.INFORMATION_MESSAGE);

        System.out.println(val);

        jd.add(jop);

    }

Helpful link:
- Why does JOptionPane.getValue() continue to return uninitializedValue
- https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html

有用的链接:
-为什么 JOptionPane.getValue() 继续返回 uninitializedValue
- https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html