Java JComponent get input map

Description

Java JComponent get input map


import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

public class Main {
   public static void main(String[] args) {
      JFrame f = new JFrame();

      JButton component = new JButton();

      MyAction action = new MyAction();

      component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
            action.getValue(Action.NAME));

      f.add(component);//w  ww  .  j  a v  a  2s. c o  m

      f.setSize(310, 200);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);
   }
}

class MyAction extends AbstractAction {
   public MyAction() {
      super("my action");
      putValue(Action.NAME, "Closes the application");
   }

   public void actionPerformed(ActionEvent e) {
      System.out.println("hi");

   }
}



PreviousNext

Related