java – 如何检测keyTypedEvent中的退格

我正在使用Netbeans的bean表单创建我的GUI.我已经将一个keyTyped事件添加到JTextArea,我想检测键入的键是否是退格键.

我出于其他原因使用keyTyped事件,所以我不能只使用keyPressed事件.

这是生成的代码(以及我的if检查):

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())来检测其值并检查它.

如何检测键入的键是退格键(或删除键)?

解决方法:

退格和删除具有以下常量:

VK_BACK_SPACE

VK_DELETE

常量列在这里:
Class KeyEvent

docs.oracle.com开始

WARNING: Aside from those keys that are defined by the Java language (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of the VK_ constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future.

除此之外,我建议您使用keyPressed()或keyReleased(),因为keyTyped()仅用于生成字符的键.键退格和删除不会产生字符.

额外:

getKeyChar()适用于KEY_TYPED,如here:所述

The getKeyChar method always returns a valid Unicode character or CHAR_UNDEFINED. Character input is reported by KEY_TYPED events: KEY_PRESSED and KEY_RELEASED events are not necessarily associated with character input.

Therefore, the result of the getKeyChar method is guaranteed to be meaningful only for KEY_TYPED events.

你可以看看这些链接:

The keyTyped() event is only used for keys that produce character input.

“Key typed” events are higher-level and generally do not depend on the platform or keyboard layout.

上一篇:如何使用NetBeans为Java Web应用程序生成sun-web.xml?


下一篇:部署错误:从netbeans到glassfish 4.0的Java-Webproject