如果我在Java程序中使用IF ELSE的每个JTextField会怎样

时间:2017-03-02 07:34:05

标签: java

这是我到目前为止编写的代码:

if (firstname.getText().length() == 0
    || lastname.getText().length() == 0
    || middlename.getText().length() == 0
    || ((JTextField) jDateChooser1.getDateEditor().getUiComponent()).getText().length() == 0
    || contactno.getText().length() == 0)

    JOptionPane.showMessageDialog(null, "One of the required field is empty!", "Error", JOptionPane.ERROR_MESSAGE);

1 个答案:

答案 0 :(得分:0)

如果你想要更好的东西,可以使用返回布尔值的方法分别检查每个字段,例如:

public boolean checkField(){
    if (firstname.getText().trim().isEmpty()){
       JOptionPane.showMessageDialog(null, "First name is required", JOptionPane.ERROR_MESSAGE);
       return false;
    }

    if (lastname.getText().isEmpty()){
       JOptionPane.showMessageDialog(null, "Last name is required", JOptionPane.ERROR_MESSAGE);
       return false;
    }
    //... 

    //if all your field is correct you can return true
    return true;
}