JOptionPane cancel button

让人想犯罪 __ 提交于 2019-12-11 07:03:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!