gpt4 book ai didi

java - 设置应用程序范围的 key 监听器

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:34:10 25 4
gpt4 key购买 nike

我如何设置应用程序范围的键监听器(键盘快捷键),以便当组合键(例如 Ctrl + Shift + T ) 被按下时,在 Java 应用程序中调用某个 Action 。

我知道键盘快捷键可以设置 JMenuBar 菜单项,但在我的例子中,应用程序没有菜单栏。

最佳答案

查看 How To Use Key Bindings Java 教程的一部分。

您需要使用组件的 ActionMap 创建并注册一个 Action 并注册一个 (KeyStroke, Action Name) 在应用程序的一个组件的 InputMap 中配对。鉴于您没有 JMenuBar,您可以简单地在应用程序中使用顶级 JPanel 注册键绑定(bind)。

例如:

Action action = new AbstractAction("Do It") { ... };

// This is the component we will register the keyboard shortcut with.
JPanel pnl = new JPanel();

// Create KeyStroke that will be used to invoke the action.
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK);

// Register Action in component's ActionMap.
pnl.getActionMap().put("Do It", action);

// Now register KeyStroke used to fire the action. I am registering this with the
// InputMap used when the component's parent window has focus.
pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "Do It");

关于java - 设置应用程序范围的 key 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1231622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com