[ACCEPTED]-How can I listen for key presses (within Java Swing) across all components?-keylistener
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 8 false allows the keyboard focus manager 7 to resume normal key event dispatching to 6 the various components.
If you want to 5 catch key combos, you can keep a set of 4 "pressed keys." Whenever a key is pressed, add 3 it to the set and check what keys are already 2 in the set. When a key is released, remove 1 it from the set.
I don't think there is a way to add a "global" key 6 listener like you are wanting to do. This 5 forum post with a similar question backs me up. You 4 are just going to have to add them to each 3 component. This should only need to be done 2 once though, so I guess you can just get 1 it over with and move on.
Very simple my friend: All you have to 6 do is create a class KeyEventDispatcher 5 and register to KeyboardFocusManager C.1
Then 4 parse and extract state and key info see: C.2 Strangely 3 enough though, you have to get the KEY STATE 2 via ThatEvent.getID();
SEEMS LIKE A MISSNOMER 1 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;
}
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.