Java 将键码转换为字符串或字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15991822/
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
Java converting keycode to string or char
提问by user2098268
I want to turn keyevent keycode value into a string or a char value. Either one would do.
我想将 keyevent 键码值转换为字符串或字符值。任何一个都可以。
For example, when I press 'SPACE', which 'lets say' has a keycode 20, and I want to convert that value to a char or a string. Is there any standard way of doing so, or I have to write a bunch of 'if' statements for every key on the keyboard?
例如,当我按“SPACE”时,“假设”的键码为 20,我想将该值转换为字符或字符串。是否有任何标准方法可以这样做,或者我必须为键盘上的每个键编写一堆“if”语句?
回答by bluevoid
Cast it to Char.
将其投射到 Char。
Char c=(Char)keycode;
回答by Reujoe
If e is the variable parameter of the KeyEvent, use
如果 e 是 KeyEvent 的可变参数,则使用
e.getKeyText(e.getKeyCode())
But preferably use it in a static context of KeyEvent
但最好在 KeyEvent 的静态上下文中使用它
KeyEvent.getKeyText(e.getKeyCode())
It returns a string but you can cast to or get value of string returned in other parsable data types
它返回一个字符串,但您可以转换为或获取其他可解析数据类型中返回的字符串的值
回答by Ankur Shanbhag
One way could be to load all the values in a Mapand just get the value for each key pressed. Like if you press a SPACE-KEY and get input as 20, just get the value associated with that key from the map and use it.
一种方法是加载 Map 中的所有值,然后获取每个按下的键的值。就像你按下一个空格键并得到 20 的输入一样,只需从地图中获取与该键关联的值并使用它。
回答by Dylan
Another option similar to Reujoe is to use getKeyChar()
if you have they KeyEvent variable.
另一个类似于 Reujoe 的选项是getKeyChar()
在您拥有 KeyEvent 变量时使用。
e.getKeyChar()
e.getKeyChar()
It returns the character representation of the keycode as a Char
它返回键码的字符表示作为 Char
回答by Peter Arbeitsloser
Just cast it to a character, but not with capital c:
只需将其转换为一个字符,但不使用大写字母 c:
char c = (char) 20;