Example usage for javax.swing SwingUtilities getUIInputMap

List of usage examples for javax.swing SwingUtilities getUIInputMap

Introduction

In this page you can find the example usage for javax.swing SwingUtilities getUIInputMap.

Prototype

public static InputMap getUIInputMap(JComponent component, int condition) 

Source Link

Document

Returns the InputMap provided by the UI for condition condition in component component.

Usage

From source file:Main.java

/**
 * A helper for creating and updating key bindings for components with
 * mnemonics. The {@code pressed} action will be invoked when the mnemonic
 * is activated and the {@code released} action will be invoked when the
 * mnemonic is deactivated./*from   ww w  . ja  v a2  s  .  c o m*/
 * <p>
 * TODO establish an interface for the mnemonic properties, such as {@code
 * MnemonicEnabled} and change signature to {@code public static <T extends
 * JComponent & MnemonicEnabled> void updateMnemonicBinding(T c, String
 * pressed, String released)}
 * 
 * @param c
 *            the component bindings to update
 * @param pressed
 *            the name of the action in the action map to invoke when the
 *            mnemonic is pressed
 * @param released
 *            the name of the action in the action map to invoke when the
 *            mnemonic is released (if the action is a toggle style, then
 *            this parameter should be {@code null})
 * @throws NullPointerException
 *             if the component is {@code null}
 */
public static void updateMnemonicBinding(JComponent c, String pressed, String released) {
    Class<?> clazz = c.getClass();
    int m = -1;

    try {
        Method mtd = clazz.getMethod("getMnemonic");
        m = (Integer) mtd.invoke(c);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new IllegalArgumentException("unable to access mnemonic", e);
    }

    InputMap map = SwingUtilities.getUIInputMap(c, JComponent.WHEN_IN_FOCUSED_WINDOW);

    if (m != 0) {
        if (map == null) {
            map = new ComponentInputMapUIResource(c);
            SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_IN_FOCUSED_WINDOW, map);
        }

        map.clear();

        //TODO is ALT_MASK right for all platforms?
        map.put(KeyStroke.getKeyStroke(m, InputEvent.ALT_MASK, false), pressed);
        map.put(KeyStroke.getKeyStroke(m, InputEvent.ALT_MASK, true), released);
        map.put(KeyStroke.getKeyStroke(m, 0, true), released);
    } else {
        if (map != null) {
            map.clear();
        }
    }
}