Why can't KeyAdapter understand shift +1 =?

To a computer:

int key = e.getKeyCode();
if(e.getKeyCode() == VK_Shift && e.getKeyCode() == VK_1){
text = "!";
}

Does nothing, but to me it should set it to an exclamation mark. Why won't this work? I am trying to make a game and in the chat box, I need text to be set to an exclamation mark when the user does Shift 1.

Jon Skeet
people
quotationmark

Why won't this work?

You're asking whether a single value (e.getKeyCode()) is equal to both VK_Shift and VK_1. Unless those two have the same value (which they don't) the if condition can never be satisfied.

The documentation makes this pretty clear:

Virtual key codes are used to report which keyboard key has been pressed, rather than a character generated by the combination of one or more keystrokes (such as "A", which comes from shift and "a").

For example, pressing the Shift key will cause a KEY_PRESSED event with a VK_SHIFT keyCode, while pressing the 'a' key will result in a VK_A keyCode. After the 'a' key is released, a KEY_RELEASED event will be fired with VK_A. Separately, a KEY_TYPED event with a keyChar value of 'A' is generated.

So in other words, you'd need to handle two KEY_PRESSED events, remembering the first one (shift) as context for the second (1).

Perhaps you should be looking for KEY_TYPED events (using KeyAdapter.keyTyped()) and using e.getKeyChar() instead.

people

See more on this question at Stackoverflow