有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在按键事件中检查JTtextField中的字符串数字验证器

我成功地验证了数值的数值,而用户键入的值为

if (evt.getKeyChar() >= '0' && evt.getKeyChar() <= '9' || (a == java.awt.event.KeyEvent.VK_BACK_SPACE) ) {
    txtPrice.setEditable(true);
    lblPriceErr.setVisible(false);
} else {
   txtPrice.setEditable(false);
   lblPriceErr.setText("* Number only");
   lblPriceErr.setVisible(true);
}

如何以同样的方式制作数字字符串验证程序


共 (2) 个答案

  1. # 1 楼答案

    您可以设置输入验证程序

    JTextField textField = new JTextField();
    textField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            String text = ((JTextField) input).getText();
            if (text.matches("\\d+")) // Reads: "Any digit one or more times"
                return true;
            return false;
        }
    });
    

    这不会阻止用户输入非数字,但文本字段不会产生焦点

  2. # 2 楼答案

    简而言之,在尝试执行文本组件的实时验证时,不要使用KeyListener

    相反,使用^{},这就是它们的设计目的。看看this的例子,包括一些“数字”过滤器的例子

    要验证String,只需使用^{}^{}。确保用try-catch包装每个容器,并用NumberFormatException捕捉容器。这将告诉您String何时无法转换为数值