Search code examples
javaswingjtextfield

Catch if there is a number in JTextField


I have tried many methods but still did not works. I tried to catch if there is a number in JTextfield it will make the string text turn to red and pop up the JOption. But my code only catches if there are numbers in both of my JTextfield. I want to my JTextField have only characters and space.

(jtf2 and jtf3 are JTextField)

if(ae.getSource() == bcreate) // create
{
    String firstname;
    String lastname;
    String id;
    firstname = jtf2.getText();
    lastname = jtf3.getText();
    try
    {
        Integer.parseInt(jtf2.getText());
        jtf2.setForeground(Color.RED);

        Integer.parseInt(jtf3.getText());
        jtf3.setForeground(Color.RED);
        JOptionPane.showMessageDialog(null, "Please enter valid character","ERROR",JOptionPane.ERROR_MESSAGE);
    }
    catch(NumberFormatException w)
    {
        create(firstname, lastname);
        jtf3.setForeground(Color.black);
        jtf2.setForeground(Color.black);

        id = Integer.toString(e.length); 
        current = Integer.parseInt(id);

        jta.setText("Employee #" + id + " " + firstname + " " + lastname + " was created.");
    }
}

Solution

  • This not the correct way to check for numbers in code. Exception is for exception condition. And here we are exploiting it and running main code in exception. Rather you should use regex to check if, text contains any number or not. As below :

    String firstname = jtf2.getText();
    String lastname = jtf3.getText();
    String id;
    
    
    boolean isInvalidText = false;
    
    if(firstname.matches(".*\\d.*")) {
      jtf2.setForeground(Color.RED);
      isInvalidText = true;
    }
    
    if(lastname.matches(".*\\d.*")) {
      jtf3.setForeground(Color.RED);
      isInvalidText = true;
    }
    
    if(isInvalidText) {
      JOptionPane.showMessageDialog(null, "Please enter valid character","ERROR",JOptionPane.ERROR_MESSAGE);
    } else {
       create(firstname, lastname);
       jtf3.setForeground(Color.black);
       jtf2.setForeground(Color.black);
    
    
       id = Integer.toString(e.length); 
                
       current = Integer.parseInt(id);
    
       jta.setText("Employee #" + id + " " + firstname + " " + lastname + " was created.");
    
    }