如何使用密钥侦听器来验证对文本字段的输入

How to use a key listener to verify input to a text field

所以我正在尝试验证输入到我的文本字段中的内容是否只是数字而非字母数字。我研究过格式化的文本框,但由于缺乏对 oracle 教程在他们网站上的理解,所以无法实现它们。我进行了更多搜索,找到了关键侦听器 class,这似乎是最佳选择。

因此,当我 运行 程序并在文本字段中键入内容而不是使用字符事件时,它只是向我发出哔哔声。这是代码:

    private void buildPanel()
{
    // Create a label to display instructions.
    messageLabel = new JLabel("Enter a time in seconds the object has fallen");

    // Create a text field 10 characters wide
    fallingTextField = new JTextField(10);

    // Add a keylistener to the text field
    fallingTextField.addKeyListener(new TextFieldListener());

    // Create a button with the caption "Calculate"
    calcButton = new JButton("Calcualte");

    // Add an action listener to the button
    calcButton.addActionListener(new CalcButtonListener());

    //Create a JPanel object and let the panel field reference it
    panel = new JPanel();

    // Add the label, text field, and button components to the panel
    panel.add(messageLabel);
    panel.add(fallingTextField);
    panel.add(calcButton);
}

/**
    The TextFieldListener class checks to see if a valid key input is typed into
    the text field.
*/
private class TextFieldListener implements KeyListener
{
    /**
        The keyPressed method
        @param evt is a key event that verifies a number is inputed otherwise
        the event is consumed.
    */
    public void keyPressed(KeyEvent evt)
    {
        char c = evt.getKeyChar();
        if(Character.isAlphabetic(c))
        {
            getToolkit().beep();
            evt.consume(); 
        }
    }
    public void keyReleased(KeyEvent e)
    {

    }
    public void keyTyped(KeyEvent ev)
    {

    }
}

这里:

if(Character.isAlphabetic(c))
    {
        getToolkit().beep();

你告诉你的听众每次输入字母字符时发出哔哔声。所以当你这样做时它会发出哔哔声。

一切都完全按照代码暗示的方式工作。

对于你问题的另一部分;查看 consume() 的 Javadoc(继承自 InputEvent)。

使用此事件,以便发起它的源不会以默认方式处理它。

你不站在事物的 来源 一边。该事件已经创建,并已发送给侦听器。在您的上下文中调用 consume() ... 不再执行任何操作。它或多或少是一个 "no op".

同样:您编写了等待键盘输入的代码,输入是字母时,它会发出哔哔声。那就是您的代码所做的 all。我假设如果你提供一个“/”,例如……什么都不会发生。如果你想验证,那么你需要一个"feedback"循环;例如,您的侦听器在检测到错误输入时可能会覆盖文本字段内容。

我认为问题是在处理事件时已经添加了角色。您需要设置没有最后一个字符的字段的值,例如:

fallingTextField.setValue(fallingTextField.getValue().substring(0, fallingTextField.getValue().length - 1))

或者,您可以使用 Oracle 站点上的示例并使用 Mask 输入,如下所示:

zipField = new JFormattedTextField(
                    createFormatter("#####"));
...
protected MaskFormatter createFormatter(String s) {
    MaskFormatter formatter = null;
    try {
        formatter = new MaskFormatter(s);
    } catch (java.text.ParseException exc) {
        System.err.println("formatter is bad: " + exc.getMessage());
        System.exit(-1);
    }
    return formatter;
}