如何在 keyTypedEvent 中检测退格 [英] How to detect backspace in a keyTypedEvent
问题描述
我正在使用 Netbeans 的 bean 形式创建我的 GUI.
我已将 keyTyped 事件添加到 JTextArea,并且我想检测键入的键是否为 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
具有以下常量:
backspace
and delete
have the following constants:
VK_BACK_SPACE
VK_DELETE
此处列出了常量:KeyEvent 类
警告:除了那些由 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.
附加:
getKeyChar()
与 KEY_TYPED
配合使用效果很好,正如前面提到的 这里:
getKeyChar()
works well with KEY_TYPED
, as mentioned here:
getKeyChar
方法总是返回一个有效的 Unicode 字符或 CHAR_UNDEFINED
.字符输入由 KEY_TYPED
事件报告:KEY_PRESSED
和 KEY_RELEASED
事件不一定与字符输入相关联.
The
getKeyChar
method always returns a valid Unicode character orCHAR_UNDEFINED
. Character input is reported byKEY_TYPED
events:KEY_PRESSED
andKEY_RELEASED
events are not necessarily associated with character input.
因此,getKeyChar
方法的结果保证仅对 KEY_TYPED
事件有意义.
Therefore, the result of the getKeyChar
method is guaranteed to be meaningful only for KEY_TYPED
events.
您可以查看以下链接:
这篇关于如何在 keyTypedEvent 中检测退格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!