Java examples for Swing:JComponent
Adds a hot key to the containing window of a Swing component.
//package com.java2s; import java.awt.event.KeyEvent; 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 { /**// w ww . j ava 2s.co m * Adds a <ctrl> 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) { addHotKey(KeyStroke.getKeyStroke(key, key == KeyEvent.VK_ESCAPE ? 0 : java.awt.event.InputEvent.CTRL_MASK), to, actionName, action); } public static void addHotKey(KeyStroke keystroke, JComponent to, String actionName, Action action) { 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); } }