KeyEvent characters

user565660 picture user565660 · Feb 27, 2012 · Viewed 8.3k times · Source

I have a question about a KeyListener. When I get the KeyEvent and do a getKeyChar() I'm tyring to compare to and * asterisk and I was going to use one of the KeyEvent.VK_ defines which works for a lot of the keys.

But for this particular key and some others the values don't match up.

The * getKeyChar() will return 0x2a and the getKeyCode() returns 0x38. The define for 0x38 is VK_8 not VK_ASTERISK which is 0x97.

Why do certain keycodes match up and not others. Most do thouh. If I just do a character compare that works( == '*'), but I'm not sure if this the best solution?

Thank you for all help!!!

Answer

Oleg Mikheev picture Oleg Mikheev · Feb 27, 2012

OK, you're misunderstanding something.

Keys are keys, and symbols are symbols. Symbols are results of key presses, and the same key can result in different symbols depending on circumstances (key combinations like Alt, Control, Shift etc).

So, VK_8 key code stands for the key that can produce symbols 8, * and possibly others depending on keyboard localization.

And the * dedicated key on numeric keyboard is VK_MULTIPLY - it can produce just one symbol * (to my knowledge).

You probably shouldn't care about the key that the user pressed, but about the symbol that this user action produced.

This info you can get with getKeyChar(), but please note that if the user presses Shift 8 combination to produce * it's actually two keys (Shift and 8) and you will get two events, and the first one (for Shift) will produce an unreadable symbol.