Reputation: 1115
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();
}
}
});
}
}
Upvotes: 0
Views: 1652
Reputation: 260
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!");
Upvotes: 2