1

Possible Duplicate:
Java - Get keycode of a char

I have a String which can contain alphabet, digits, +, -, = etc. I want to get the key code of each character so that I can use that in KeyEventData() argument. I am able to detect only alphanumeric characters.

How do I detect a keypress such as +, :, }, etc. which requires a shift key press?

Community
  • 1
  • 1
DarkKnight
  • 243
  • 1
  • 4
  • 10
  • Are you getting this string through actual keypress events? What exactly are you trying to do? – Shmiddty Aug 22 '12 at 23:20
  • The "extended" key presses are combinations of a basic virtual key and shift state. So "+" would be `VK_EQUALS` + `SHIT_DOWN_MASK` – MadProgrammer Aug 22 '12 at 23:22
  • No. It is a predefined string. I want to simulate a key press event based on its value so that I can enter that value in JXTreeTable cell. – DarkKnight Aug 22 '12 at 23:22
  • @MadProgrammer : so I need to determine for each character whether its an extended key press or not. – DarkKnight Aug 22 '12 at 23:23
  • @DarkKnight unfortunately yes :P - I did a massively long switch statement that would, given a char, return a a key sequence (essentially a list of key strokes) required to replicate the char. Every Google search I did basically come back to the same conclusion. If you have better luck, I'd love to know! – MadProgrammer Aug 22 '12 at 23:28

2 Answers2

1

In the KeyEvent you receive as parameter in a KeyListener -I am assuming you are using this listener-, you have the methods getKeyCode() and getKeyChar().

gersonZaragocin
  • 1,122
  • 12
  • 20
  • No. I am not accepting string from keyboard. It is predefined in the program. – DarkKnight Aug 22 '12 at 23:25
  • @gersonZaragocin Also, `getKeyChar` isn't guaranteed to return a result (I believe `keyTyped` does, can't remember if it's `keyPressed` or `keyReleased` that returns an empty char). `KeyCode` is only useful if you have the extended state (shift, alt, ctrl) of the keystroke (in this context) – MadProgrammer Aug 22 '12 at 23:31
1

Use AWTKeyStroke.getKeyStroke:

assert KeyEvent.VK_A == AWTKeyStroke.getAWTKeyStroke("pressed A").getKeyCode();
  && KeyEvent.VK_COLON
    == AWTKeyStroke.getAWTKeyStroke("pressed COLON").getKeyCode();
  && KeyEvent.VK_BRACERIGHT
    == AWTKeyStroke.getAWTKeyStroke("pressed BRACERIGHT").getKeyCode();
obataku
  • 29,212
  • 3
  • 44
  • 57