Para las personas preguntándose (como yo) cómo utilizar KeyEventDispatcher, aquí es un ejemplo que puse juntos. Utiliza un HashMap para almacenar todas las acciones globales, porque no me gustan las construcciones grandes if (key == ..) then .. else if (key == ..) then .. else if (key ==..) ..
.
/** map containing all global actions */
private HashMap<KeyStroke, Action> actionMap = new HashMap<KeyStroke, Action>();
/** call this somewhere in your GUI construction */
private void setup() {
KeyStroke key1 = KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK);
actionMap.put(key1, new AbstractAction("action1") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Ctrl-A pressed: " + e);
}
});
// add more actions..
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
kfm.addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
if (actionMap.containsKey(keyStroke)) {
final Action a = actionMap.get(keyStroke);
final ActionEvent ae = new ActionEvent(e.getSource(), e.getID(), null);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
a.actionPerformed(ae);
}
});
return true;
}
return false;
}
});
}
El uso de SwingUtils.invokeLater() es tal vez no es necesario, pero es probablemente una buena idea de no bloquear el bucle de eventos global.
+1 Lo mejor, respuesta más fácil que he encontrado. Voy a renunciar a este x1000 –
x1001 sería mejor, de esa manera al menos recibiría un voto favorable. – Epaga
@Epaga O 999 veces –