Sharing an InputMap or an ActionMap Between Two Components : Actions « Swing JFC « Java






Sharing an InputMap or an ActionMap Between Two Components

   

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) {
    InputMap im = new JTextArea().getInputMap(JComponent.WHEN_FOCUSED);
    im.put(KeyStroke.getKeyStroke("F2"), "actionName");

    ActionMap am = new JTextArea().getActionMap();
    am.put("actionName", new AbstractAction("actionName") {
      public void actionPerformed(ActionEvent evt) {
        System.out.println((JTextComponent) evt.getSource());
      }
    });
    im.put(KeyStroke.getKeyStroke("F3"), "actionName2");
    am.put("actionName2", new AbstractAction("actionName2") {
      public void actionPerformed(ActionEvent evt) {
        System.out.println((JTextComponent) evt.getSource());
      }
    });
    JButton component1 = new JButton("button 1");
    JButton component2 = new JButton("button 2");

    component1.setInputMap(JComponent.WHEN_FOCUSED, im);
    component2.setInputMap(JComponent.WHEN_FOCUSED, im);

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



  }
}

   
    
    
  








Related examples in the same category

1.Action DemoAction Demo
2.Creating an Action
3.Enabling an Action
4.UseActions: MenuUseActions: Menu
5.Action events are fired by subclasses of AbstractButton and includes buttons, checkboxes, and menus.
6.Listing the Actions in a Component
7.Apply special filter to a JTextField
8.Listing the Key Bindings in a Component
9.A text component has an action map with actions and keymaps with actions
10.extends AbstractAction to create your won actionextends AbstractAction to create your won action