所以我想验证输入到我的文本字段中的内容只有数字而不是字母数字。我研究过格式化的文本框,但由于缺乏对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)
{
}
}
唐为了爱的理智,不要使用'KeyListener',而是使用'DocumentListener',而不是使用'DocumentFilter',它就是它的设计目的 – MadProgrammer
另一个注意事项:当格式化工具不起作用...那么不要放弃它。只要继续阅读并学习如何使用那个东西。你看,你遇到了一个问题,并决定放弃。不要这样做。你通过**解决**难题学习编程;而不是通过交换另一个...... – GhostCat
当用户将文本粘贴到字段中时会发生什么? (暗示没有) – MadProgrammer