Java: handling combined keyboard input
-
03-07-2019 - |
Question
What is the correct way to separate between F1 and i.e. CTRL+F1 respective SHIFT-CTRL+F1 within an KeyListener registered behind i.e. a JButton?
public void keyPressed(KeyEvent event) {
int key = event.getKeyCode();
logger.debug("KeyBoard pressed char(" + event.getKeyChar() + ") code (" + key + ")");
}
.. always gives me 112 for F1, 113 for F2 and so on. I understand that I can handle it by taking care of the keyPressed() respective for keyReleased for CTRL / SHIFT / ALT / etc on my own, but I hope that there is a better way.
Many many thanks!!!
Solution
The Solution lies in the parent of KeyEvent (InputEvent)
- Use the isAltDown,isControlDown,isShiftDown methods or
- Use the getModifiers method
OTHER TIPS
Since KeyEvent extends InputEvent, isControlDown, isShiftDown and isAltDown.
KeyEvent
s are probably a bit low-level when dealing with a Swing widget. Instead go through InputMap
and ActionMap
.
The key down event is called whenever a key is down, obviously. Its not a multiple key down event, and there is no such thing, so there is no keycode for multiple keys being down.
You are just going to have to use a variable to keep track of the crtl key being pressed. This means you are also going to have to use a key up event to keep track of when the control key is released.
In pusedo code:
// CRTLKeyCode is whatever the code is for the ctrl key private boolean ctrlPressed = false; onKeyDown(KeyEvent event){ int key = event.getKeyCode(); if(key == CRTLKeyCode) ctrlPressed = true; else if(ctrlPressed && key == 112) //Perform your action } onKeyUp(KeyEvent event){ int key = event.getKeyCode(); if(key == CRTLKeyCode) ctrlPressed = false; }