如何在按下键的事件中检查textField中的字符串数字验证

时间:2014-04-30 03:39:00

标签: java validation

当用户将值键入为

时,我成功验证了数值的数值
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 个答案:

答案 0 :(得分:0)

简短回答,在尝试对文本组件进行实时验证时不要使用KeyListener

相反,请使用DocumentFilter,这就是他们的设计目标。请查看this示例,其中包含一些“数字”过滤器示例。

要验证String,您只需使用Double.parseDoubleInteger.parseInt即可。确保将每个包裹在try-catch中并捕获NumberFormatException。这将告诉您何时String无法转换为数值。

答案 1 :(得分:0)

您可以设置输入验证程序

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;
    }
});

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