Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: handling combined keyboard input

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!!!

like image 494
MrG Avatar asked Dec 30 '08 18:12

MrG


People also ask

How do we get input from the keyboard when using Java?

Accepting keyboard input in Java is done using a Scanner object. This statement declares a reference variable named console. The Scanner object is associated with standard input device (System.in).

How do you check if a key is being pressed in Java?

Use KeyEvent. getKeyChar() and KeyEvent. getKeyCode() to find out which key the user pressed.

How do you use key events in Java?

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.


1 Answers

The Solution lies in the parent of KeyEvent (InputEvent)

  1. Use the isAltDown,isControlDown,isShiftDown methods or
  2. Use the getModifiers method
like image 78
Midhat Avatar answered Sep 24 '22 21:09

Midhat