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

前端 未结 3 1018
面向向阳花
面向向阳花 2020-12-19 05:28

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.

相关标签:
3条回答
  • 2020-12-19 05:42

    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);
    
    0 讨论(0)
  • 2020-12-19 05:59

    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.

    Correct. If a component has focus and implements the same binding then that binding will have preference.

    If you don't want that binding to be applicable for the text area then you need to remove the binding from the text area.

    Read the section from the Swing tutorial on How to Use Key Bindings for explanations of the various InputMaps that you can use and for an example on how to remove a binding.

    0 讨论(0)
  • 2020-12-19 05:59

    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.

    0 讨论(0)
提交回复
热议问题