Listening to key events for a component hierarchy

前端 未结 4 850
抹茶落季
抹茶落季 2021-01-18 12:11

I have a Swing app that needs to display different sets of controls based on whether the control or alt keys are pressed. I added a KeyListener to the main component, but i

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 12:45

    You may consider using the InputMap and ActionMap of some swing components. You can specify with JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT to indicate you want to respond to the given keystroke when either the component or its subcomponents are in focus.

    If you don't want to use the InputMap or ActionMap, you could just add the KeyListener to all the child components:

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

提交回复
热议问题