-1

I used below code in the constructor of JFrame. But it's only working when none of the frame components is focused.

this.getActionMap().put("doSomething",actions);
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK),"doSomething");
thiis.getActionMap().put("doSomething",actions);`
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Tibin Tomy
  • 29
  • 6
  • 2
    This question is very confusing because 1) It mentions the FQN of the AWT frame in the title, yet goes on to discuss the Swing frame in the text. 2) Key bindings were never meant for AWT components. 3) It has no question. 4) The code snippet which includes `thiis.getActionMap()..` would never compile. - Voting to close. – Andrew Thompson Mar 08 '17 at 13:06
  • This worked for me: https://stackoverflow.com/a/67650493/2441655 – Venryx May 22 '21 at 14:17

1 Answers1

1

But it's only working when none of the frame components is focused.

Correct. You are using the InputMap for when the component has focus. If you want the binding to be active even when the component doesn't have focus you need to use a different InputMap. Read the section from the Swing tutorial How Key Bindings Work for the 3 different InputMap types.

How to make key bindings for java.awt.Frame and for all its components?

Key Bindings work on Swing components, not AWT components.

You should add the bindings to the JRootPane of the JFrame:

frame.getRootPane().getInputMap(...)...
frame.getRootPane().getActionMap()...
camickr
  • 321,443
  • 19
  • 166
  • 288
  • I just want to perform the action when i press ctrl + A even if the jframe component is focused or not . – Tibin Tomy Mar 09 '17 at 05:20
  • @TibinTomy, you can't do this in Java. Swing can only manage events when the frame has focus. You will need to use JNA or JNI (which I know nothing about), if you want to listen for OS events. – camickr Mar 09 '17 at 05:59