java KeyPressed 和 KeyTyped 混淆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17797231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 15:01:13  来源:igfitidea点击:

KeyPressed and KeyTyped Confusion

javaawtkeypresskeylistener

提问by user2583511

I have searched about difference between KeyPressedand KeyTypedEvents but still I'm not clear about that . One thing I have found is Keypressed is triggered first than KeyTyped . Please clarify me when these are triggered exactly . Which is appropriate to use for which purpose ? Thanks in advance

我已经搜索了KeyPressedKeyTypedEvents之间的区别,但我仍然不清楚。我发现的一件事是 Keypressed 先触发而不是 KeyTyped 。当这些被准确触发时,请澄清我。哪个适合用于哪个目的?提前致谢

回答by tbodt

keyPressedis fired whenever any key press occurs. keyTypedis fired when a key is pressed that can be converted into a unicode character. If the shift key is down, for example, pressing "a" will tell keyTypedthat you typed a capital A, and keyPressedwill just get the "a" key, without capital or lowercase designations. You cannot call event.getKeyChar()from keyPressed, because there is no key char associated with the events. Characters only come from keyTyped.

keyPressed每当发生任何按键按下时都会触发。keyTyped当按下可以转换为 unicode 字符的键时触发。例如,如果按下 shift 键,则按“a”会告诉keyTyped您输入的是大写 A,并且keyPressed只会得到“a”键,没有大写或小写指定。您不能event.getKeyChar()从调用keyPressed,因为没有与事件关联的键字符。字符仅来自keyTyped.

The basic idea is that keyTypedis used to find characters that are typed, and keyPressedis used for obtain raw key presses.

基本思想是keyTyped用于查找键入的字符,并keyPressed用于获取原始按键。

回答by Russell Uhl

KeyPressedhappens when the key goes down. KeyTypedhappens when the key goes down and then back up. I'm not sure if "in rapid succession" is a requirement, and if it is, how fast "rapid" is.

KeyPressed当键下降时发生。 KeyTyped当钥匙下降然后备份时发生。我不确定“快速连续”是否是一个要求,如果是,“快速”有多快。

Edit: KeyTypedis actually when a unicode char is sent from the keyboard. USUALLY, the key behavior is that it goes down and then back up in rapid succession.

编辑:KeyTyped实际上是从键盘发送 unicode 字符时。通常,关键行为是它下降然后快速连续回升。

Taken from: KeyListener, keyPressed versus keyTyped

取自:KeyListener、keyPressed 与 keyTyped