所以我正在尝试验证输入到我的文本字段中的内容只是数字而不是字母数字。我已经研究过格式化的文本框,但由于缺乏对 oracle 教程在他们网站上的理解,所以无法实现它们。我进行了更多搜索,找到了关键的监听器类,这似乎是最佳选择。
因此,当我运行程序并在文本字段中键入内容而不是使用字符事件时,它只会向我发出哔哔声。这是代码:
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()
... 不再执行任何操作。这或多或少是一种“无操作”。
同样:您编写了等待键盘输入的代码,当输入是字母时,它会发出哔哔声。这就是您的代码所做的全部。我假设如果你提供一个“/”,例如……什么都不会发生。如果你想验证,那么你需要一个“反馈”循环;例如,您的监听器在检测到错误输入时可能会覆盖文本字段内容。
关于java - 如何使用 key 监听器来验证对文本字段的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42244580/