JOptionPane取消按钮

时间:2013-06-03 11:33:49

标签: java swing joptionpane cancel-button

伙计我试图使用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; 
    }
}

3 个答案:

答案 0 :(得分: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");
  }
}

看看它是否适合你:)

答案 1 :(得分: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; 
}

}

答案 2 :(得分:0)

作为旁注,我认为误导JOptionPane(第11行)应该不必要地提出例外。