简体   繁体   English

Java验证

[英]Java Validation

I have a Form with a few textfields and a save button. 我有一个带有几个文本字段和一个保存按钮的表单。 When the buttton is pressed, it should be checked whether certain textfields are empty, and if those are empty, then an error message should be displayed, else whatever job needed should be performed. 当按下按钮时,应检查某些文本字段是否为空,如果文本字段为空,则应显示错误消息,否则应执行所需的任何工作。 i have written the code for that, but whether the fields are empty or not, it performs the main tasks. 我已经为此编写了代码,但是无论字段是否为空,它都会执行主要任务。 Could someone advise please? 有人可以建议吗? thanks 谢谢

final JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        if(textField_2.equals("") || textField_3.equals("") || textField_4.equals("") || textField_5.equals("") || textField_6.equals("") || textArea.equals("") || textField_7.equals("")) {
            JOptionPane.showMessageDialog(frmModifyBooking, "Please fill in all fields indicated with a star (*).");
        }
        else {
            try {
                String sql = "UPDATE vacation SET `StaffID` =?, `From` =?, `To` =?, `TotalDays` =?, `VacationType` =?, `Notes` =?, `Signature` =?, `Date` =? WHERE VacationID = ?";
                PreparedStatement prest = con.prepareStatement(sql);
                prest.setString(1, textField_1.getText());
                prest.setString(2, textField_2.getText());
                prest.setString(3, textField_3.getText());
                prest.setString(4, textField_4.getText());
                prest.setString(5, textField_5.getText());
                prest.setString(6, textArea.getText());
                prest.setString(7, textField_6.getText());
                prest.setString(8, textField_7.getText());
                prest.setString(9, txtAUniqueStudent.getText());
                prest.executeUpdate();
                JOptionPane.showMessageDialog(frmModifyBooking, "Record has been updated.");
            }
            catch (SQLException e) {
                //System.out.println("Record couldn't be added!");
                e.printStackTrace();
                JOptionPane.showMessageDialog(frmModifyBooking, "Record couldn't be updated. Please try again.");
            }
        }
    }
});
button.setBounds(280, 402, 89, 23);
panel_1.add(button);

With textField_2.equals("") you are comparing the object not the JTextFields text. 使用textField_2.equals("")您正在比较对象而不是JTextFields文本。

Simply use: 只需使用:

textField_2.getText().equals("")...

Did you mean: 你的意思是:

textField_2.getText().equals("") etc.

which you could also write: 您也可以这样写:

textField_2.getText().isEmpty() etc.

I feel like it's because you're comparing an entire FIELD to the empty string. 我觉得这是因为您正在将整个FIELD与空字符串进行比较。 Try comparing the values instead. 尝试比较这些值。

if (textField_1.getText().equals(''))

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

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