catch如果jtextfield中有数字

bzzcjhmw  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(414)

我试过很多方法,但还是不管用。我试图捕捉jtextfield中是否有数字,它将使字符串文本变为红色并弹出joption。但我的代码只有在两个jtextfield中都有数字时才会被捕获。我希望我的jtextfield只有字符和空格。
(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.");
    }
}
kkih6yb8

kkih6yb81#

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

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

}

相关问题