How can a KeyListener detect key combinations (e.g., ALT + 1 + 1)

You should not use KeyListener for this type of interaction. Instead use key bindings, which you can read about in the Java Tutorial. Then you can use the InputEvent mask to represent when the various modifier keys are depresed. For example: // Component that you want listening to your key JComponent component = …; component.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, … Read more

How can I listen for key presses (within Java Swing) across all components?

It is possible. KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(KeyEvent e) { System.out.println(“Got key event!”); return false; } }); That will grab all key events. Returning false allows the keyboard focus manager to resume normal key event dispatching to the various components. If you want to catch key combos, you can keep a set … Read more

java keylistener not called

I’ll bet that you’re requesting focus before the JPanel has been rendered (before the top level window has either had pack() or setVisible(true) called), and if so, this won’t work. Focus request will only be possibly granted after components have been rendered. Have you checked what your call to requestFocus() has returned? It must return … Read more

Swing’s KeyListener and multiple keys pressed at the same time

Use a collection to remember which keys are currently pressed and check to see if more than one key is pressed every time a key is pressed. class MultiKeyPressListener implements KeyListener { // Set of currently pressed keys private final Set<Integer> pressedKeys = new HashSet<>(); @Override public synchronized void keyPressed(KeyEvent e) { pressed.add(e.getKeyCode()); Point offset … Read more