1

伙计们,我正在尝试使用 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; 
    }
}
4

3 回答 3

2

这是你想要的吗:

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");
  }
}

看看它是否适合你:)

于 2013-06-03T12:06:32.110 回答
0

作为旁注,我认为拼写错误JOptionPane(在第 11 行)应该会引发不必要的异常。

于 2013-06-03T11:59:44.570 回答
0

显示 OptionDialog 后,您必须使用 break 语句来中断循环。JOptionPane 不知道您的循环。

或使用

System.exit(ErrorCode);

代替break;

更新

所以我认为你想要的是这样的:

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; 
}

}

于 2013-06-03T11:40:58.783 回答