import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.KeyStroke; public class Main { public static void main(String[] argv) throws Exception { JButton component = new JButton(); MyAction action = new MyAction(); component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put( KeyStroke.getKeyStroke("F2"), action.getValue(Action.NAME)); } } class MyAction extends AbstractAction { public MyAction() { super("my action"); } public void actionPerformed(ActionEvent e) { System.out.println("hi"); } }