Java Swing Key Action parseKeyStroke(String keyStroke)

Here you can find the source of parseKeyStroke(String keyStroke)

Description

Converts a string to a keystroke.

License

Open Source License

Parameter

Parameter Description
keyStroke A string description of the key stroke

Declaration

public static final KeyStroke parseKeyStroke(String keyStroke) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.KeyStroke;

public class Main {
    /**//from   ww  w.  j a  v  a 2  s.c o m
     * Converts a string to a keystroke. The string should be of the
     * form <i>modifiers</i>+<i>shortcut</i> where <i>modifiers</i>
     * is any combination of A for Alt, C for Control, S for Shift
     * or M for Meta, and <i>shortcut</i> is either a single character,
     * or a keycode name from the <code>KeyEvent</code> class, without
     * the <code>VK_</code> prefix.
     *
     * @param keyStroke A string description of the key stroke
     */
    public static final KeyStroke parseKeyStroke(String keyStroke) {

        if (keyStroke == null) {
            return (null);
        }

        int modifiers = 0;
        int ch = '\0';
        int index = keyStroke.indexOf('+');
        for (int i = 0; i < index; i++) {

            switch (Character.toUpperCase(keyStroke.charAt(i))) {
            case 'A':
                modifiers |= InputEvent.ALT_MASK;
                break;
            case 'C':
                modifiers |= InputEvent.CTRL_MASK;
                break;
            case 'M':
                modifiers |= InputEvent.META_MASK;
                break;
            case 'S':
                modifiers |= InputEvent.SHIFT_MASK;
                break;
            }
        }

        String key = keyStroke.substring(index + 1);
        if (key.length() == 1) {
            ch = Character.toUpperCase(key.charAt(0));
        } else if (key.length() == 0) {
            System.err.println("Invalid key stroke: " + keyStroke);
            return (null);
        } else {
            try {
                ch = KeyEvent.class.getField("VK_".concat(key)).getInt(null);
            } catch (Exception e) {
                System.err.println("Invalid key stroke: " + keyStroke);
                return (null);
            }
        }

        return (KeyStroke.getKeyStroke(ch, modifiers));
    }
}

Related

  1. keyStrokeToString(KeyStroke key)
  2. keyStrokeToString(KeyStroke key)
  3. makeCloseAction(final Window window)
  4. matches(Action action, KeyEvent ke)
  5. parseKeyStroke(String keyStroke)
  6. pressKey(Component component, int keyCode, int modifier)
  7. registerKey(JComponent component, final int keyEvent, int modifiers, Action action)
  8. registerKeyAction(JComponent component, int keyCode, Action action)
  9. registerTabKey(Container container)