简体   繁体   English

从JOptionPane获得良好的输入

[英]Getting good input from a JOptionPane

I'm trying to get a user to enter an integer into a JOptionPane, and need a way to make sure the user inputs an integer. 我试图让用户在JOptionPane中输入整数,并且需要一种方法来确保用户输入整数。 Could I use a while loop for this, and if so how do I implement this? 我可以为此使用while循环吗,如果可以,该如何实现呢?

You could do something like this: 您可以执行以下操作:

boolean taken = false;
int myInteger = 0;
while(!taken){
   String s = (String)JOptionPane.showInputDialog(this, "Your question", "Your window title", JOptionPane.PLAIN_MESSAGE, null, null, "");

   //Check if input is an integer
   try{
      myInteger = Integer.parseInt(s);
      taken = true;
   catch(NumberFormatException e){
      taken = false;
   }
}

in a loop : use a try-catch statement for a MalFormedNumeberException in the try you use the JOptionPane to get input trim the use the parse from the Integer class then if success a break in the catch: print the exception using printStackTrace method or show message that inform user to input valid number format 在循环中:在尝试使用JOptionPane获取输入修剪的尝试中,对MalFormedNumeberException使用try-catch语句,使用Integer类的解析,然后如果成功中断了:使用printStackTrace方法打印异常或显示消息通知用户输入有效的数字格式

     while(true){
        try{
                 //here the JOptionPane input
                 //here the parseInt from Integer class
                 break;
            }catch(NumberFormatException e){
                 //JOptionPane with show message dialogue asking for valide input
            }
       }

There are a number of ways you might achieve this, my personal preference is to take control over what the user can enter, for example, using a JSpinner ... 您可以通过多种方式实现这一目标,我个人的偏好是控制用户可以输入的内容,例如使用JSpinner ...

JPanel questionPanel = new JPanel();
questionPanel.add(new JLabel("Place enter a number:"));
JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 5));
questionPanel.add(spinner);
Integer result = null;
int exitValue = JOptionPane.OK_OPTION;
do {
    exitValue = JOptionPane.showConfirmDialog(null, questionPanel, "Guess", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    result = (Integer) spinner.getValue();
} while (result == null && exitValue != JOptionPane.CANCEL_OPTION);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM