如何在 keyTypedEvent 中检测退格 [英] How to detect backspace in a keyTypedEvent

查看:14
本文介绍了如何在 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)?

推荐答案

backspacedelete 具有以下常量:

backspace and delete have the following constants:

VK_BACK_SPACE

VK_DELETE

此处列出了常量:KeyEvent 类

来自 docs.oracle.com

警告:除了那些由 Java 语言定义的键(VK_ENTERVK_BACK_SPACEVK_TAB),不要依赖VK_ 常量的值.Sun 保留根据需要更改这些值的权利,以适应未来更广泛的键盘.

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() 仅用于产生人物.键 backspacedelete 不产生字符.

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_PRESSEDKEY_RELEASED 事件不一定与字符输入相关联.

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.

因此,getKeyChar 方法的结果保证仅对 KEY_TYPED 事件有意义.

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

您可以查看以下链接:

keyTyped() 事件仅用于产生字符输入的键.

键入的键"事件是更高级别的,通常不依赖于平台或键盘布局.

这篇关于如何在 keyTypedEvent 中检测退格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆