简体   繁体   English

如何检查 jFormattedTextField 是否为空?

[英]How to check if a jFormattedTextField is empty?

I saw some similiar questions about this one, but, none of them seems to be helping me here.我看到了一些关于这个问题的类似问题,但是,在这里似乎没有一个对我有帮助。

I have a jFormattedTextField with this mask "##-##-####", and i get date to send to a PostgreSQL with dd-MM-yyyy, This field is for birth date.我有一个带有此掩码“##-##-####”的 jFormattedTextField,并且我使用 dd-MM-yyyy 将日期发送到 PostgreSQL,该字段用于出生日期。

When I was using normal jTextfield and the user had to input "/" or "-" to separate day, month and year, it was ok to check if it was empty, however, with the mask on, i'm not able to check.当我使用普通的 jTextfield 并且用户必须输入“/”或“-”来分隔日、月和年时,可以检查它是否为空,但是,在打开掩码的情况下,我无法查看。

else if (jFormattedTextFieldDATA.getText().equals(""))
                {
                    JOptionPane.showMessageDialog(null,"Por favor completar o campo Data"); //please complete date field

            try {
                conecta.conn.setAutoCommit(false);
                conecta.conn.rollback();
            } catch (SQLException ex) {
                Logger.getLogger(Pessoa.class.getName()).log(Level.SEVERE, null, ex);
            }

And, here it's where the netbeans says the mistake is:而且,这就是 netbeans 说错误的地方:

SimpleDateFormat formatter  = new SimpleDateFormat ("dd-MM-yyyy");
        java.util.Date utilDate = null;
                try {
                    utilDate = formatter.parse(jFormattedTextFieldDATA.getText());
                } catch (ParseException ex) {
                   Logger.getLogger(Pessoa.class.getName()).log(Level.SEVERE, null, ex);
                }
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
        pst.setDate(5, sqlDate);
        pst.executeUpdate(); //executa o SQL

this is what a get from netbeans:这是从 netbeans 得到的:

java.lang.NullPointerException: Cannot invoke "java.util.Date.getTime()" because "utilDate" is null java.lang.NullPointerException:无法调用“java.util.Date.getTime()”,因为“utilDate”为空

The JFormattedTextField should already be configured with a SimpleDateFormatter which will be doing the parsing/formatting/validation of the text. JFormattedTextField应该已经配置了SimpleDateFormatter ,它将对文本进行解析/格式化/验证。

In this case, you should be using getValue instead of getText在这种情况下,您应该使用getValue而不是getText

java.util.Date utilDate = jFormattedTextFieldDATA.getValue();
if (utilDate != null) {
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    pst.setDate(5, sqlDate);
} else {
    // I don't know what you want to do in this case...
}
pst.executeUpdate(); //executa o SQL

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

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