How can I listen for key presses (within Java Swing) across all components?
I would like to listen for key combinat开发者_Go百科ions such as Control+S without adding key listeners to each component in my Swing application. How can I achieve this?
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.
I don't think there is a way to add a "global" key listener like you are wanting to do. This forum post with a similar question backs me up. You are just going to have to add them to each component. This should only need to be done once though, so I guess you can just get it over with and move on.
Very simple my friend: All you have to do is create a class KeyEventDispatcher and register to KeyboardFocusManager C.1
Then parse and extract state and key info see: C.2 Strangely enough though, you have to get the KEY STATE via ThatEvent.getID();
SEEMS LIKE A MISSNOMER TO ME.
/////////////////////////////////////////////////////////////////////////////////////////// C.1)
KeyDispatcher ThisKeyDispatcher = new KeyDispatcher();
KeyboardFocusManager ThisKbFocusMngr = KeyboardFocusManager
. getCurrentKeyboardFocusManager();
ThisKbFocusMngr . addKeyEventDispatcher(ThisKeyDispatcher);
return ThisKeyDispatcher;
///////////////////////////////////////////////////////////////////////////////////////////
C.2
public static class KeyDispatcher implements KeyEventDispatcher {
public boolean dispatchKeyEvent(final KeyEvent ThatEvent) {
KeyboardFocusManager ThisKbFocusMngr = null;
Component ThisComponent = null;
Container ThisRoot = null;
Window ThisWindow = null;
int ThisKeyStateEvent = 0;
try {
ThisKbFocusMngr = KeyboardFocusManager . getCurrentKeyboardFocusManager();
ThisComponent = ThisKbFocusMngr . getFocusOwner();
ThisRoot = ThisKbFocusMngr . getCurrentFocusCycleRoot();
ThisWindow = ThisKbFocusMngr . getActiveWindow();
ThisKeyStateEvent = ThatEvent.getID(); // i.e. KeyEvent.KEY_RELEASED
if(false == ThatEvent.isConsumed()) {
boolean RetBool = false;
if((KeyEvent.VK_BACK == ThatEvent.getKeyCode())) {
RetBool = true;
} else {
RetBool = m_CallSomeoneEvent(ThatEvent);
}
if(RetBool) {
ThatEvent.consume();
return true;
}
}
}
catch( Throwable e ) {
LogThis(". ", e);
}
return false;
}
}
精彩评论