Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Universal Key Code (Java)

Tags:

java

keyboard

Hi I'm programming a listener that based on the key pressed by the user, must act in a certain manner.

I need to be able to determine if a user press the I key or M key. Actually I'm doing it like:

// If pressed the 'i' key
if ( evt.getKeyCode() == 73) {
    //
}
...

I look out here and with the sample applet determine that the I key is recognized as a 73 code.

That works.

But I'm working at Mac OS X, and I don't know if once I try to run this app on another OS or just JVM, It won't work.

Is the 73 a universal key code? Is there a certain way to program this so it can run and determine the key pressed, on windows.

Thank you!

like image 619
Sheldon Avatar asked Jan 26 '10 17:01

Sheldon


2 Answers

Oh, you're looking for the KeyEvent.VK_Whatever constants.

if ( evt.getKeyCode() == KeyEvent.VK_I) {
    // user pressed 'i'
} else if ( evt.getKeyCode() == KeyEvent.VK_M) {
    // user pressed 'm'
}

See KeyEvent API docs for the rest. Should make sense.

like image 99
Paul Brinkley Avatar answered Oct 23 '22 13:10

Paul Brinkley


Just complementing Paul Brinkley's answer.

Is the 73 a universal key code?

Yes, it is the ASCII code of the upper case letter, 'I' in that case. See the javadoc for KeyEvent.VK_A

Attention

despite this coincidence, it's better not to do something like getKeyCode() == 'A' - it may fail in future implementations.

like image 33
user85421 Avatar answered Oct 23 '22 12:10

user85421