8

How do we make key bindings for a JFrame regardless of what's in focus in the frame?

I already looked at this question: How do you make key bindings for a java.awt.Frame?

I tried setting the input map for the root pane of the JFrame, but it doesn't work when the focus is on a JTextArea even though editable is false.

What's the easiest way to make key bindings work across an entire JFrame?

4

3 回答 3

7

你可以尝试使用JComponent#getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)

来自Java 文档

用于 registerKeyboardAction 的常量,这意味着当接收组件位于具有焦点的窗口中或本身就是焦点组件时,应调用该命令。

于 2013-11-01T03:14:20.223 回答
6

正如@camickr 所写,您不应该在文本区域上也绑定相同的键。

现在,这是一个实现:

// Action action = ...
// KeyStroke stroke = ...

JRootPane rootPane = mainJFrame.getRootPane();
rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "myAction");
rootPane.getActionMap().put("myAction", action);
于 2014-11-04T13:59:40.363 回答
5

我尝试为 JFrame 的根窗格设置输入映射,但是当焦点位于 JTextArea 上时它不起作用,即使可编辑为 false。

正确的。如果组件具有焦点并实现相同的绑定,则该绑定将具有优先权。

如果您不希望该绑定适用于文本区域,则需要从文本区域中删除该绑定。

阅读 Swing 教程中有关如何使用键绑定的部分,以了解您可以使用的各种 InputMap 的解释以及有关如何删除绑定的示例。

于 2013-11-01T03:24:56.073 回答