Search code examples
javajformattedtextfield

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.

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.

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:

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:

java.lang.NullPointerException: Cannot invoke "java.util.Date.getTime()" because "utilDate" is null


Solution

  • The JFormattedTextField should already be configured with a SimpleDateFormatter which will be doing the parsing/formatting/validation of the text.

    In this case, you should be using getValue instead of 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