Java Swing Key Action addHotKey(int key, JComponent to, String actionName, Action action)

Here you can find the source of addHotKey(int key, JComponent to, String actionName, Action action)

Description

Adds a control hot key to the containing window of a component.

License

Open Source License

Parameter

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

Declaration

public static void addHotKey(int key, JComponent to, String actionName, Action action) 

Method Source Code

//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);
        }
    }
}

Related

  1. addActionsToMap(Action[] list1, Map h)
  2. addCloseActionWithEscapeKey(final Window window, JRootPane rootPane)
  3. addCtrlEnterAction(JComponent comp, AbstractAction action)
  4. addEnterKey(JComponent control)
  5. addEscKeyAction(javax.swing.JComponent component, javax.swing.InputMap inputMap, javax.swing.Action action)
  6. addIcons(Action action, String[][] iconRoles)
  7. addStrokeToName(Action action)
  8. augmentList(Action[] list1, Action[] list2)
  9. dispatchEvent(final KeyEvent ke, final Component comp)