问题
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!
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;
}
}
回答1:
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 :)
回答2:
As a side note, I think mispelling JOptionPane
(on line 11) should raise exceptions needlessly.
回答3:
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.
Or use
System.exit(ErrorCode);
instead of a 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;
}
}
来源:https://stackoverflow.com/questions/16895775/joptionpane-cancel-button