Here you can find the source of addHotKey(int key, JComponent to, String actionName, Action action)
Parameter | Description |
---|---|
key | one of the KeyEvent keyboard constants |
to | component to map to |
actionName | unique action name for the component's action map |
action | callback to notify when control key is pressed |
public static void addHotKey(int key, JComponent to, String actionName, Action action)
//package com.java2s; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.KeyStroke; public class Main { /**/* ww w .j a va 2s . c om*/ * Adds a control hot key to the containing window of a component. * In the case of buttons and menu items it also attaches the given action to the component itself. * * @param key one of the KeyEvent keyboard constants * @param to component to map to * @param actionName unique action name for the component's action map * @param action callback to notify when control key is pressed */ public static void addHotKey(int key, JComponent to, String actionName, Action action) { KeyStroke keystroke = KeyStroke.getKeyStroke(key, java.awt.event.InputEvent.CTRL_MASK); InputMap map = to.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); map.put(keystroke, actionName); to.getActionMap().put(actionName, action); if (to instanceof JMenuItem) { ((JMenuItem) to).setAccelerator(keystroke); } if (to instanceof AbstractButton) /// includes JMenuItem/ { ((AbstractButton) to).addActionListener(action); } } }