Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to listen for key combinations such as Control+S without adding key listeners to each component in my Swing application. How can I achieve this?

like image 770
diolemo Avatar asked Mar 17 '11 20:03

diolemo


People also ask

What is key listener interface in Java?

Interface KeyListenerThe listener interface for receiving keyboard events (keystrokes). The class that is interested in processing a keyboard event either implements this interface (and all the methods it contains) or extends the abstract KeyAdapter class (overriding only the methods of interest).


1 Answers

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 of "pressed keys." Whenever a key is pressed, add it to the set and check what keys are already in the set. When a key is released, remove it from the set.

like image 143
Matt Wonlaw Avatar answered Sep 20 '22 03:09

Matt Wonlaw