【问题标题】:Catch if there is a number in JTextField捕获 JTextField 中是否有数字
【发布时间】:2021-03-16 04:07:22
【问题描述】:

我尝试了很多方法,但仍然没有奏效。我试图捕捉 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.");
    }
}

【问题讨论】:

标签: java swing jtextfield


【解决方案1】:

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

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

}

【讨论】:

  • 加 1 用于解释如何使用异常。
猜你喜欢
  • 2011-10-17
  • 1970-01-01
  • 2014-10-19
  • 2014-04-02
  • 1970-01-01
  • 2017-03-24
  • 2014-02-12
  • 2019-08-02
  • 2017-04-08
相关资源
最近更新 更多