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?

Charles
  • 50,943
  • 13
  • 104
  • 142
user2098268
  • 121
  • 2
  • 2
  • 7
  • 4
    Do you mean something like [KeyEvent.getKeyText()](http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyText%28int%29)? – Michał Kosmulski Apr 13 '13 at 19:18

5 Answers5

13

Cast it to Char.

Char c=(Char)keycode;
Dylan
  • 2,161
  • 2
  • 27
  • 51
bluevoid
  • 1,274
  • 13
  • 29
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

Reujoe
  • 81
  • 1
  • 2
2

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

char c = (char) 20;
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.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
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

Dylan
  • 2,161
  • 2
  • 27
  • 51