【问题标题】:Validate textfield input in GUI在 GUI 中验证文本字段输入
【发布时间】:2014-04-30 16:31:09
【问题描述】:

我有两个文本字段,单击提交时它们必须加起来为 100,如果我在文本字段中输入正确的值,则没有错误,但如果我将文本字段留空或在其中输入字母,则错误处理是不对。有什么想法吗?

submit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        if (validation == true) {
            int numA = Integer.parseInt(aTextField.getText());
            int numB = Integer.parseInt(aTextField.getText());
            int sum = numA + numB;

            if (sum == 100) {
                validation = true;
                System.out.println("success");
            } else {
                JOptionPane.showMessageDialog(createFrame, "A and B must add up to 100");
                validation = false;

            }


        }

这是错误

int numA = Integer.parseInt(aTextField.getText());

【问题讨论】:

标签: java validation user-interface


【解决方案1】:

如果解析到方法中的String 无法转换为数字,Integer.parseInt(str); 会抛出NumberFormatException(您看到的错误)。

您可以在这种特殊情况下使用一些异常处理。我建议使用trycatch 块。例如;

   try{
       if(validation == true){
            int numA = Integer.parseInt(aTextField.getText());
            int numB = Integer.parseInt(aTextField.getText());
            int sum = numA + numB;

            if(sum == 100){
                validation = true;
                System.out.println("success");
            } else{
                JOptionPane.showMessageDialog(createFrame, "A and B must add up to 100");
                validation = false;
            }
        }
    } catch (NumberFormatException n){
            JOptionPane.showMessageDialog(createFrame, "Only numbers should be entered into A and B");
            validation = false;
    }

如果现在从try 块中抛出异常,它将被“捕获”,然后验证将在catch 块中设置为false。您还可以使用 catch 块显示一条消息,说明只能在字段中输入数字。

使用 Swing API 实现此目的的另一种方法是,如果您不希望他们永远在这些字段中输入文本,您可以使用 JFormattedTextField 让他们只输入数字。

我希望这会有所帮助。让我知道你的进展情况。

【讨论】:

  • @user3103074 - 没问题。很高兴我能帮上忙。 :)
【解决方案2】:

检查javadoc of Integer.parseInt!该函数无法处理空字符串。那应该是多少?

可能的解决方案:

  • 将文本字段的默认文本设置为“0”

  • 为 parseInt 调用添加异常处理(您可以回退到 0或提示用户更正)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多