Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make key binding for a JFrame no matter what JComponent is in focus?

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?

like image 587
trusktr Avatar asked Nov 01 '13 03:11

trusktr


2 Answers

You could try using JComponent#getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)

From the Java Docs

Constant used for registerKeyboardAction that means that the command should be invoked when the receiving component is in the window that has the focus or is itself the focused component.

like image 193
MadProgrammer Avatar answered Nov 15 '22 21:11

MadProgrammer


As @camickr wrote, you should not have the same key also bound on you text area.

Now, here is an implementation:

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

JRootPane rootPane = mainJFrame.getRootPane();
rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "myAction");
rootPane.getActionMap().put("myAction", action);
like image 43
Juh_ Avatar answered Nov 15 '22 19:11

Juh_