通用密钥代码 (Java)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2141400/
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-10-29 19:39:20  来源:igfitidea点击:

Universal Key Code (Java)

javakeyboard

提问by Sheldon

Hi I'm programming a listener that based on the key pressed by the user, must act in a certain manner.

嗨,我正在编写一个基于用户按下的键的监听器,它必须以某种方式运行。

I need to be able to determine if a user press the Ikey or Mkey. Actually I'm doing it like:

我需要能够确定用户是否按下了I键或M键。其实我是这样做的:

// If pressed the 'i' key
if ( evt.getKeyCode() == 73) {
    //
}
...

I look out hereand with the sample applet determine that the Ikey is recognized as a 73 code.

我在这里查看并使用示例小程序确定I密钥被识别为 73 代码。

That works.

这样可行。

But I'm working at Mac OS X, and I don't know if once I try to run this app on another OS or just JVM, It won't work.

但是我在 Mac OS X 上工作,我不知道一旦我尝试在另一个操作系统或 JVM 上运行这个应用程序,它就行不通。

Is the 73 a universal key code? Is there a certain way to program this so it can run and determine the key pressed, on windows.

73 是通用钥匙码吗?是否有某种方法可以对此进行编程,以便它可以在 Windows 上运行并确定按下的键。

Thank you!

谢谢!

采纳答案by user85421

Just complementing Paul Brinkley's answer.

只是补充保罗布林克利的回答

Is the 73 a universal key code?

73 是通用钥匙码吗?

Yes, it is the ASCIIcode of the upper case letter, 'I' in that case. See the javadoc for KeyEvent.VK_A

是的,它是大写字母的ASCII代码,在这种情况下是“I”。请参阅KeyEvent.VK_A的 javadoc

Attention

注意力

despite this coincidence, it's better not to do something like getKeyCode() == 'A'- it may fail in future implementations.

尽管有这种巧合,但最好不要做类似的事情getKeyCode() == 'A'- 它可能会在未来的实现中失败。

回答by Paul Brinkley

Oh, you're looking for the KeyEvent.VK_Whatever constants.

哦,您正在寻找 KeyEvent.VK_Whatever 常量。

if ( evt.getKeyCode() == KeyEvent.VK_I) {
    // user pressed 'i'
} else if ( evt.getKeyCode() == KeyEvent.VK_M) {
    // user pressed 'm'
}

See KeyEvent API docs for the rest. Should make sense.

其余的请参阅 KeyEvent API 文档。应该是有道理的。

回答by trashgod

As others have suggested, using constants from KeyEventis the right way to go. You might enjoy looking at source of this game; it's a KeyEventbonanza. Although Java has excellent cross-platform support, you're smart to test. I've used two major approaches:

正如其他人所建议的那样,使用常量 fromKeyEvent是正确的方法。您可能会喜欢查看此游戏的来源;这是一个KeyEvent富矿。尽管 Java 具有出色的跨平台支持,但您还是很聪明地进行测试。我使用了两种主要方法:

  • Post open source demos and ask for feedback.
  • Run other operating systems in Sun's VirtualBox.
  • 发布开源演示并寻求反馈。
  • 在 Sun 的VirtualBox 中运行其他操作系统。