java JOptionPane 取消按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16895775/
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
JOptionPane cancel button
提问by MikeSHR
Guys Im trying to use the JOptionPane but the cancel button is responding as if I entered a wrong input value and does not exit the programm. Any ideas whould be very useful!
伙计们 我正在尝试使用 JOptionPane 但取消按钮正在响应,好像我输入了错误的输入值并且没有退出程序。任何想法都非常有用!
int n = 0, k = 0;
Students stu = new Students();
while (n <= 0) {
try {
n = Integer.parseInt(JOptionPane.showInputDialog(stu, "Enter the number of people","Input", JOptionPane.INFORMATION_MESSAGE));
if (n <= 0) {
OptionPane.showMessageDialog(stu, "You have given a wrong input!",
"Warning", JOptionPane.WARNING_MESSAGE);
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(stu, "You have given a wrong input!",
"Warning", JOptionPane.WARNING_MESSAGE);
n = 0;
}
}
回答by A-SM
Is this what you wanted:
这是你想要的吗:
int n;
String code = JOptionPane.showInputDialog(null,
"Enter the size of the group",
"Team Combination Finder",
JOptionPane.INFORMATION_MESSAGE);
if (code == null) {
System.out.println("This is cancel button");
System.exit(0);
} else if (code.equalsIgnoreCase("")) {
System.out.println("This is OK button without input");
} else {
try {
n = Integer.parseInt(code);
if (n <= 0) {
System.out.println("This is wrong input");
} else {
System.out.println("This is right input");
}
} catch (Exception e) {
System.out.println("You must input numeric only");
}
}
See if it works for you :)
看看它是否适合你:)
回答by Devolus
After you have shown the OptionDialog you must use a break statement, in order to break the loop. JOptionPane doesn't know about your loop.
在显示 OptionDialog 之后,您必须使用 break 语句来中断循环。JOptionPane 不知道您的循环。
Or use
或使用
System.exit(ErrorCode);
instead of a break;
代替 break;
update
更新
So I think what you want is this:
所以我想你想要的是这个:
String input = JOptionPane.showInputDialog(null, "Enter name : ", "New Record!",
while (n <= 0) {
try {
String input = JOptionPane.showInputDialog(stu, "Enter the number of people","Input", JOptionPane.INFORMATION_MESSAGE);
if(input == null || input.length() == 0)
{
OptionPane.showMessageDialog(stu, "You have given a wrong input!",
"Warning", JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
n = Integer.parseInt(input);
if (n <= 0) {
OptionPane.showMessageDialog(stu, "You have given a wrong input!",
"Warning", JOptionPane.WARNING_MESSAGE);
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(stu, "You have given a wrong input!",
"Warning", JOptionPane.WARNING_MESSAGE);
n = 0;
}
}
}
回答by Aeronth
As a side note, I think mispelling JOptionPane
(on line 11) should raise exceptions needlessly.
作为旁注,我认为拼写错误JOptionPane
(第 11 行)应该会引发不必要的异常。