Java 有没有办法在 JOptionPane showInputDialog 中只有 OK 按钮(没有 CANCEL 按钮)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16511039/
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
Is there a way to only have the OK button in a JOptionPane showInputDialog (and no CANCEL button)?
提问by Coffee_Table
I've seen that this is possible in other types of dialog windows such as "showConfirmDialog", where one can specify the amount of buttons and their names; but is this same functionality achievable when using "showInputDialog"? I couldn't seem to find this type of thing in the API. Perhaps I just missed it, but any help is appreciated.
我已经看到这在其他类型的对话框窗口中是可能的,例如“showConfirmDialog”,其中可以指定按钮的数量及其名称;但是在使用“showInputDialog”时是否可以实现相同的功能?我似乎无法在 API 中找到这种类型的东西。也许我只是错过了它,但感谢任何帮助。
采纳答案by Eng.Fouad
Just add a custom JPanel as a message to JOptionPane.showOptionDialog()
:
只需添加一个自定义 JPanel 作为消息到JOptionPane.showOptionDialog()
:
String[] options = {"OK"};
JPanel panel = new JPanel();
JLabel lbl = new JLabel("Enter Your name: ");
JTextField txt = new JTextField(10);
panel.add(lbl);
panel.add(txt);
int selectedOption = JOptionPane.showOptionDialog(null, panel, "The Title", JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options , options[0]);
if(selectedOption == 0)
{
String text = txt.getText();
// ...
}
回答by Maroun
JOptionPane.showInputDialog()
returns the string the user has entered if the user clicks "OK" and returns null
otherwise. See this:
JOptionPane.showInputDialog()
如果用户单击“确定”,则返回用户输入的字符串,null
否则返回。看到这个:
Returns: user's input, or null meaning the user canceled the input
返回: 用户的输入,或 null 表示用户取消输入
You can't do this using showInputDialog()
你不能这样做 showInputDialog()
However, you can use JOptionPane#showOptionDialog():
但是,您可以使用JOptionPane#showOptionDialog():
Object[] buttons = {"OK"};
int res = JOptionPane.showOptionDialog(yourFrame,
"YourMessage","YourTitle",
JOptionPane....,
JOptionPane..., null, buttons , buttons[0]);
As @HovercraftFullOfEels stated on the comments, you can add JTextField
to the dialog and achieve this.
正如@HovercraftFullOfEels 在评论中所述,您可以添加JTextField
到对话框中并实现此目的。