Pour les gens se demander (comme moi) comment utiliser KeyEventDispatcher, voici un exemple que je mets ensemble. Il utilise un HashMap pour stocker toutes les actions globales, parce que je n'aime pas les grandes constructions 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;
}
});
}
L'utilisation de SwingUtils.invokeLater() est peut-être pas nécessaire, mais il est probablement une bonne idée de ne pas bloquer la boucle d'événement mondial.
+1 La meilleure, réponse la plus facile je l'ai trouvé. Je vais upvote ce x1000 –
x1001 serait mieux, de cette façon, il aurait au moins un upvote. – Epaga
@Epaga Ou 999 fois –