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