Sharing an InputMap or an ActionMap Between Two Components - Java Swing

Java examples for Swing:Event

Description

Sharing an InputMap or an ActionMap Between Two Components

Demo Code

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.JTextComponent;

public class Main {
  public static void main(String[] argv) throws Exception {
    // 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());
      }//from   w  w  w  . ja va  2  s .co  m
    });

    JButton component1 = null;
    JButton component2 = null;
    // Use the shared InputMap and ActionMap
    component1.setInputMap(JComponent.WHEN_FOCUSED, im);
    component2.setInputMap(JComponent.WHEN_FOCUSED, im);

    component1.setActionMap(am);
    component2.setActionMap(am);

    im.put(KeyStroke.getKeyStroke("F3"), "actionName2");
    am.put("actionName2", new AbstractAction("actionName2") {
      public void actionPerformed(ActionEvent evt) {
       // process((JTextComponent) evt.getSource());
      }
    });
  }
}

Related Tutorials