0

I have a JFormattedTextField that is meant for user to enter phone number. My phone number is taking the following format :+### ###-###-###. I want to check for empty string before I save the phone number to a database. The problem is I am not able to check/determine if the field is empty. When I print field.getText().length() it outputs 16 meaning some characters are already in the field. How do I check if the user has entered some characters?

Below is my code:

public class JTextFiledDemo {

private JFrame frame;

JTextFiledDemo() throws ParseException {
    frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(300, 300);
    frame.setLayout(new GridLayout(4, 1));
    frame.setLocationRelativeTo(null);
    iniGui();
}

private void iniGui() throws ParseException {

    JButton login = new JButton("Test");
    JFormattedTextField phone = new JFormattedTextField(new MaskFormatter(
            "+### ###-###-###"));

    frame.add(phone);
    frame.add(login);
    frame.pack();

    login.addActionListener((ActionEvent) -> {

        JOptionPane.showMessageDialog(frame, "The length of input is :"
                + phone.getText().length());

    });

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                JTextFiledDemo tf = new JTextFiledDemo();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
      }

   }
CN1002
  • 1,115
  • 3
  • 20
  • 40
  • 2
    Use a `java.text.Format` instead of a `MaskFormatter` (see [this question](http://stackoverflow.com/a/13424140/1076463)) and the problem will disappear. – Robin May 11 '15 at 12:09
  • @Robin Well, thanks let me look into it, for now I have used the answer below – CN1002 May 11 '15 at 12:32

1 Answers1

2

You can used the isEditValid() method to check the contents

 final boolean editValid = phone.isEditValid();
 showMessageDialog(frame, "The length of input is :" + phone.getText().length() + ".  It is " + (editValid ? "" : "not ") + "valid!");
Nik
  • 250
  • 1
  • 11