如何在keyTypedEvent中检测退格 [英] How to detect backspace in a keyTypedEvent
问题描述
我正在使用Netbeans的bean表单来创建我的GUI.
我已经向JTextArea添加了keyTyped事件,并且我想检测键入的键是否为 Backspace .
I'm using Netbeans' bean form to create my GUI.
I've added a keyTyped event to a JTextArea and I want to detect if the typed key is a Backspace.
由于其他原因,我正在使用keyTyped事件,所以我不能只使用keyPressed事件.
I'm using keyTyped event for other reasons so I cannot just use the keyPressed event.
这是生成的代码(和我的if检查):
This is the generated code (and my if check):
private void langArea1KeyTyped(java.awt.event.KeyEvent evt) {
if(evt.getChar()== backspace) //how can I make this check?
}
evt.getKeyCode()
始终返回0,与键入的键无关.
evt.getKeyChar()
只是删除打印时打印的最后一个字符,所以我不能使用System.out.print(evt.getKeyChar())
来检测其值并进行检查.
evt.getKeyCode()
always returns 0 independent of the typed key.
evt.getKeyChar()
simply deletes the last character printed when printed so I can't use System.out.print(evt.getKeyChar())
to detect its value and check for it.
如何检测键入的密钥是 Backspace (还是 Delete )?
How can I detect if the typed key is Backspace (or Delete)?
推荐答案
backspace
和delete
具有以下常量:
VK_BACK_SPACE
VK_DELETE
常数在这里列出: 类KeyEvent
Constants are listed here: Class KeyEvent
From docs.oracle.com
警告:除了Java语言(
VK_ENTER
,VK_BACK_SPACE
和VK_TAB
)定义的那些键外,不要依赖VK_
常量的值. Sun保留根据需要更改这些值的权利,以在将来适应更大范围的键盘.
WARNING: Aside from those keys that are defined by the Java language (
VK_ENTER
,VK_BACK_SPACE
, andVK_TAB
), do not rely on the values of theVK_
constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future.
除此之外,我建议您使用keyPressed()
或keyReleased()
,因为keyTyped()
仅用于产生字符的键.键backspace
和delete
不产生字符.
Aside from that, I suggest you use keyPressed()
or keyReleased()
since keyTyped()
is only used for keys that produce characters. Keys backspace
and delete
do not produce characters.
其他: