Listening for key events for a component hierarchy

I have a Swing application that should display different sets of controls based on keystrokes or Alt. I added a KeyListener to the main component, but it is only notified if this component is selected, and not if a subcomponent is selected. Is there a way to listen for events for a component and all descendants?

Edit:

I tried using the main component of InputMap, but when the modifier key is pressed, no event is fired. In particular, I have the following code:

InputMap inputMap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(KeyStroke.getKeyStroke("pressed CONTROL"), "test1");
inputMap.put(KeyStroke.getKeyStroke("released CONTROL"), "test2");
ActionMap actionMap = panel.getActionMap();
actionMap.put("test1", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("pressed");
    }
});
actionMap.put("test2", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("released");
    }
});

, "", "". InputMap, , - .

+5
4

getKeyStroke(...) :

InputMap inputMap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, KeyEvent.CTRL_DOWN_MASK, false), "test1");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, 0, true), "test2");
ActionMap actionMap = panel.getActionMap();
actionMap.put("test1", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("pressed");
    }
});
actionMap.put("test2", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("released");
    }
});

, .

getInputMap (JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT), .

KeyEvent.CTRL_DOWN_MASK, KeyEvent.VK_CONTROL PRESS events. .

+4

, , KeyListeners. - , , "", , KeyListeners. Swing:

+2

InputMap ActionMap swing. JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, , , .

If you do not want to use InputMap or ActionMap, you can simply add a KeyListener to all child components:

for (Component child : parent.getComponents())
{
 child.addKeyListener(keyListener);
}
+2
source

You might be able to use the Global Event Listener .

+1
source

All Articles