捕获 JTextField 中是否有数字

Catch if there is a number in JTextField

我试了很多方法还是不行。我试图捕捉 JTextfield 中是否有数字,它会使字符串文本变为红色并弹出 JOption。但是我的代码只有在我的两个 JTextfield 中都有数字时才会捕获。我希望我的 JTextField 只有字符和 space.

(jtf2 和 jtf3 是 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.");
    }
}

这不是在代码中检查数字的正确方法。异常是异常条件。在这里,我们正在利用它和 运行 异常中的主要代码。相反,您应该使用正则表达式来检查文本是否包含任何数字。如下:

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.");

}