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, , - .