سؤال

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?

هل كانت مفيدة؟

المحلول

Cast it to Char.

Char c=(Char)keycode;

نصائح أخرى

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

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

char c = (char) 20;

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.

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top