如何在所有组件中监听按键(在Java Swing中)? [英] How can I listen for key presses (within Java Swing) across all components?
问题描述
我想要监听键组合,例如 Control + S ,而不是在Swing应用程序中为每个组件添加键侦听器。我怎样才能做到这一点?
I would like to listen for key combinations such as Control+S without adding key listeners to each component in my Swing application. How can I achieve this?
推荐答案
这是可能的。
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
System.out.println("Got key event!");
return false;
}
});
这将获取所有关键事件。返回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.
这篇关于如何在所有组件中监听按键(在Java Swing中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!