Java Swing InputMap put KeyStroke
import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.InputMap; 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(); InputMap inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke("F2"),action.getValue(Action.NAME)); f.add(component);//from ww w.ja va 2s. com 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"); } }