Java converting keycode to string or char
Asked Answered
S

5

8

I want to turn keyevent keycode value into a string or a char value. Either one would do.

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?

Stratigraphy answered 13/4, 2013 at 19:14 Comment(1)
Do you mean something like KeyEvent.getKeyText()?Gaynell
S
13

Cast it to Char.

Char c=(Char)keycode;
Slangy answered 13/4, 2013 at 19:19 Comment(1)
that was simple O_O Thanks!Stratigraphy
V
8

If e is the variable parameter of the KeyEvent, use

 e.getKeyText(e.getKeyCode())

But preferably use it in a static context of 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

Veratrine answered 24/7, 2016 at 16:46 Comment(0)
N
2

Just cast it to a character, but not with capital c:

char c = (char) 20;
Nutritionist answered 14/5, 2020 at 16:6 Comment(0)
E
1

One way could be to load all the values in a Map and 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.

Erl answered 13/4, 2013 at 19:19 Comment(0)
R
0

Another option similar to Reujoe is to use getKeyChar() if you have they KeyEvent variable.

e.getKeyChar()

It returns the character representation of the keycode as a Char

Ricardo answered 8/10, 2019 at 18:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.