views:

461

answers:

3

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!

+8  A: 

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.

Paul Brinkley
Thank you very much!
Sheldon
+1  A: 

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.

Carlos Heuberger
+1  A: 

As others have suggested, using constants from KeyEvent is the right way to go. You might enjoy looking at source of this game; it's a KeyEvent bonanza. Although Java has excellent cross-platform support, you're smart to test. I've used two major approaches:

  • Post open source demos and ask for feedback.
  • Run other operating systems in Sun's VirtualBox.
trashgod