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

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

推荐答案

backspacedelete具有以下常量:

VK_BACK_SPACE

VK_DELETE

常数在这里列出: 类KeyEvent

Constants are listed here: Class KeyEvent

来自 docs.oracle .com

From 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方法始终返回有效的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天全站免登陆