Đối với những người tự hỏi (như tôi) làm thế nào để sử dụng KeyEventDispatcher, đây là một ví dụ mà tôi đặt lại với nhau. Nó sử dụng một HashMap để lưu trữ tất cả các hành động toàn cầu, bởi vì tôi không thích các cấu trúc lớn 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;
}
});
}
Việc sử dụng SwingUtils.invokeLater() có thể không cần thiết, nhưng có lẽ không nên chặn vòng lặp sự kiện toàn cầu.
Nguồn
2011-12-13 07:52:07
+1 tốt nhất, câu trả lời đơn giản nhất tôi đã tìm thấy. Tôi sẽ upvote x1000 –
x1001 này sẽ tốt hơn, theo cách đó anh ta ít nhất sẽ có được một upvote. – Epaga
@Epaga Hoặc 999 lần –