KeyTypedEvent KeyEvent的KeyCode始终为0? [英] KeyTypedEvent KeyEvent's KeyCode is always 0?

查看:549
本文介绍了KeyTypedEvent KeyEvent的KeyCode始终为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NetBeans IDE中有一个Java Swing应用程序。

I have a Java Swing application in the NetBeans IDE.

我制作了一个表单并将KeyListener附加到我的各种控件中:

I made a form and attached a KeyListener to my various controls as such:

    jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyTyped(java.awt.event.KeyEvent evt) {
            keyTypedEvent(evt);
        }
    });

keyTypedEvent 定义如下: / p>

and keyTypedEvent is defined as such:

private void keyTypedEvent(java.awt.event.KeyEvent evt) 
{                               
System.out.println(evt);
appendDisplay(String.valueOf(evt.getKeyChar()));
} 

我添加了 println evt ,看看会发生什么,并验证我的keylistener是否有效。
当我构建并运行我的应用程序时,我意识到输出似乎总是 keycode = 0

I added a println to the evt to see what happens and to verify that my keylistener does work. When I build and run my application, I realized that the output always seems to have a keycode = 0

为了验证这一点,我将println更改为 evt.getKeyCode()并且它始终返回0.

To verify this, I had changed my println to be evt.getKeyCode() and it is always returning 0.

我可能完全误解了KeyCode的功能,但我认为它可以与Oracle文档中的值进行协调:

I could be completely misinterpreting what KeyCode does, but I thought that it would coorespond with the values in Oracle's documentation here:

http://docs.oracle.com/javase/7/docs/api /constant-values.html#java.awt.event.KeyEvent.VK_ESCAPE

例如,VK_ESCAPE的值为27.

For instance, VK_ESCAPE has a value of 27.

推荐答案

keyTyped()事件仅用于生成字符输入的键。如果您想知道何时按下或释放任何键,您需要实现 keyPressed() keyReleased()

The keyTyped() event is only used for keys that produce character input. If you want to know when any key is pressed or released, you need to implement keyPressed() or keyReleased().

来自 KeyEvent API:


键入类型事件是更高级别的,通常不依赖于
平台或键盘布局。它们是在输入Unicode
字符时生成的,并且是查找
字符输入的首选方法....

"Key typed" events are higher-level and generally do not depend on the platform or keyboard layout. They are generated when a Unicode character is entered, and are the preferred way to find out about character input....

对于密钥按下和键释放的事件,getKeyCode方法返回
事件的keyCode。对于键类型事件,getKeyCode方法
始终返回VK_UNDEFINED。

For key pressed and key released events, the getKeyCode method returns the event's keyCode. For key typed events, the getKeyCode method always returns VK_UNDEFINED.

这篇关于KeyTypedEvent KeyEvent的KeyCode始终为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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