By sharing an InputMap or ActionMap, any change to the shared InputMap or ActionMap will affect all components sharing the InputMap or ActionMap. WHEN_FOCUSED and WHEN_ANCESTOR_OF_FOCUSED_COMPONENT types of InputMaps can be shared. WHEN_IN_FOCUSED_WINDOW InputMaps cannot be shared.

    // Get an InputMap from the desired type of component and initialize it
    InputMap im = new JTextArea().getInputMap(JComponent.WHEN_FOCUSED);
    im.put(KeyStroke.getKeyStroke("F2"), "actionName");
    
    // Get an ActionMap from the desired type of component and initialize it
    ActionMap am =  new JTextArea().getActionMap();
    am.put("actionName",
        new AbstractAction("actionName") {
            public void actionPerformed(ActionEvent evt) {
                process((JTextComponent)evt.getSource());
            }
        }
    );
    
    // Use the shared InputMap and ActionMap
    component1.setInputMap(JComponent.WHEN_FOCUSED, im);
    component2.setInputMap(JComponent.WHEN_FOCUSED, im);
    
    component1.setActionMap(am);
    component2.setActionMap(am);
    
    // Now, any change to the shared InputMap or ActionMap will affect both component1 and component2
    im.put(KeyStroke.getKeyStroke("F3"), "actionName2");
    am.put("actionName2",
        new AbstractAction("actionName2") {
            public void actionPerformed(ActionEvent evt) {
                process((JTextComponent)evt.getSource());
            }
        }
    );
    

 

Related Examples

相关文章:

  • 2022-12-23
  • 2021-10-14
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2021-10-24
  • 2021-09-29
  • 2021-06-06
猜你喜欢
  • 2021-06-19
  • 2021-12-12
  • 2021-08-12
  • 2022-12-23
  • 2021-08-05
  • 2021-10-10
  • 2022-12-23
相关资源
相似解决方案