How to make key binding for JFrame no matter what JComponent is in focus?

How do we make key bindings for a JFrame no matter what is in focus in the frame?

I already examined this question: How to make key bindings for java.awt.Frame?

I tried to set an input map for the JFrame root panel, but it does not work when the focus is on JTextArea, although the editable value is false.

What is the easiest way to make key bindings work across the entire JFrame?

+4
source share
3 answers

I tried to set an input map for the JFrame root panel, but it does not work when the focus is on JTextArea, although the editable value is false.

Correctly. If the component has focus and implements the same binding, then binding will be preferable.

, , .

Swing InputMaps, , .

+3

JComponent#getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)

Java

, registerKeyboardAction, , , , .

+5

@camickr, , .

, :

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

JRootPane rootPane = mainJFrame.getRootPane();
rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "myAction");
rootPane.getActionMap().put("myAction", action);
+3

All Articles