【问题标题】:Display message dialog if JTextField does not contain data如果 JTextField 不包含数据,则显示消息对话框
【发布时间】:2012-11-20 14:57:05
【问题描述】:

我正在编写一个 BMI 计算器应用程序。目前,如果我没有在一个字段中输入数据,则会发生错误,导致程序停止工作。例如,“高度”有两个 JTextFIeld,一个是英尺,另一个是英寸。如果我只是在英尺 JTextField 中输入 '6' 而在英寸 JTextField 中不输入任何内容,然后在重量 JTextField 中输入我的体重并单击计算,它不起作用。

如果一个字段不包含数据,我想要做的是显示一个消息对话框,说“请确保所有字段都已填写”。

下面是添加到我的“计算”按钮的 ActionHandler 代码。

public void actionPerformed(ActionEvent e) {
    double heightFT = ((Double.parseDouble(heightFt_TF.getText()));
    double heightIn = (Double.parseDouble(heightIn_TF.getText()));
    double weight = (Double.parseDouble(weight_TF.getText()));
    double totalHeight = (heightFT*12) + heightIn;              
            
    BMI = (weight / (totalHeight*totalHeight)) * 703;
    String s = BMI+"";
    s = s.substring(0,4);
    BMI_TF.setText(s);                              
}

已解决

我现在已经解决了这个问题。我所做的是在方法中添加“抛出 NumberFormatException”并尝试捕获。在 try 代码块中,如果输入了所有数据字段,我编写了要执行的代码。在 catch 子句中,我编写了使用 NumberFormatException 的代码并简单地显示带有错误消息的消息对话框。现在,如果没有输入一个字段,则会出现消息对话框!

【问题讨论】:

  • 应验证您引用的 JTextfields(非空、非空、非数字)

标签: java exception exception-handling jtextfield


【解决方案1】:

只需检查您的 JTextField 对象是否包含文本。 例如:

if (heightFt_TF.getText() == null || heightIn_TF.getText() == null || weight_TF.getText() == null) {
JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in");
}

当然,您还必须确保文本字段的内容确实包含一个数字。

【讨论】:

  • Matthias,我试过了,但得到以下错误:线程“AWT-EventQueue-0”中的异常 java.lang.NumberFormatException:空字符串
【解决方案2】:

下载 Apache Commons Lang 库并使用 StringUtils.isBlank(myTextField.getText()); 验证您的字段。

public boolean validateFields() {
    if (StringUtils.isBlank(heightFt_TF.getText()) {
        // show message
        return false;
    }

    if (StringUtils.isBlank(weight_TF.getText()) {
        // show message
        return false;
    }

    return true;
}

仅当 validateFields() 返回 true 时才运行计算。

【讨论】:

    【解决方案3】:
    public boolean validate(JTextField field) {
    
      boolean result = field.getText() != null;
      if (result) {
        try {
          Double.parseDouble(field.getText()));
        } catch(NumberFormatException e) {
          result = false
        } 
      }
      return result;                    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-09
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多