Swing中如何忽略按键事件?
我想让文本字段只接受用户的数字和退格按钮。
我添加了用于检查用户的键码的功能,但我不知道如果键码不是数字,如何停止按键事件。
我需要在函数中添加什么代码来停止事件?
private void jTextField2KeyPressed(java.awt.event.KeyEvent evt)
{
if(!((evt.getKeyCode()==8) || (evt.getKeyCode()>48 && evt.getKeyCode()<57)))
{
//how to stop the key pressed event
}
}
I want to make the text field only accept numeric and backspace button from the user.
I have added the function that use to check the keycode from the user, but I don't know how to stop the key press event if the keycode is not numeric.
What code do I need to add into the function to stop the event??
private void jTextField2KeyPressed(java.awt.event.KeyEvent evt)
{
if(!((evt.getKeyCode()==8) || (evt.getKeyCode()>48 && evt.getKeyCode()<57)))
{
//how to stop the key pressed event
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您无需搞乱 Swing 事件处理即可实现此目的。
最好的方法是使用 JFormattedTextField 代替。
有关详细信息,请参阅 Java 教程:
http://docs.oracle.com/ javase/tutorial/uiswing/components/formattedtextfield.html
You don't need to mess with the Swing event handling to achieve this.
The best way is to use a JFormattedTextField instead.
See the Java tutorial for details:
http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html
尝试覆盖
keyTyped
:更新:
如果您希望粘贴不起作用并强制键入输入,您可以使用以下内容。
Try overriding
keyTyped
:Update:
In case you want pasting to not work and enforce the input to be typed, you can use the following.
设置文本字段的
PlainDocument
的DocumentFilter
。样本:
set the
DocumentFilter
of thePlainDocument
of the text field.Sample:
我建议您查看是否可以使用 keyPressed、KeyReleased 和 KeyTyped 事件,并查看它们是否会阻止按键到达您的程序。
您的程序可能只查找一种类型的关键事件,但您需要找出它是哪一种并使用这些事件。
I would suggest that you see if you can consume keyPressed,KeyReleased, and KeyTyped events, and see if they prevent the key reaching your program.
Your program is probably only looking out for 1 type of key event but you need to find out which one it is and consume those events.
你可以试试这个:
You could try this:
请参阅 Limit TextField input to numeric value - 我认为这正是您所寻找的为了。
我认为您的代码不起作用的原因是 if 语句不正确并且实际上没有捕获非数字键代码。不过,我不确定,因为我自己没有看到或测试过你的代码,所以如果你真的愿意,你可以进行一些调试,但说实话,这里发布的解决方案将是最简单的。
See Limit TextField input to numeric value - I think it is exactly what you are looking for.
I think the reason your code does not work is because the if statement is incorrect and isn't actually catch non numeric key codes. Though, I'm not sure because I haven't seen or tested your code myself so you could do some debuging if you really wanted to, but to be honest the solutions posted here will be simplest.