Java Swing Key Action stringToKey(String s)

Here you can find the source of stringToKey(String s)

Description

Construct a new key description from a given universal string description.

License

Sun Public License Notice

Parameter

Parameter Description
s the string with the description of the key

Return

key description object, or null if the string does not represent any valid key

Declaration

public static KeyStroke stringToKey(String s) 

Method Source Code

//package com.java2s;
/*/*from   ww w. j  a v  a  2 s. c o m*/
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

import java.awt.event.KeyEvent;

import java.util.*;

import java.lang.reflect.*;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;

import javax.swing.KeyStroke;

public class Main {
    /** reference to map that maps allowed key names to their values (String, Integer) 
    and reference to map for mapping of values to their names */
    private static Reference namesAndValues;

    /** Construct a new key description from a given universal string
    * description.
    * Provides mapping between Emacs-like textual key descriptions and the
    * <code>KeyStroke</code> object used in Swing.
    * <P>
    * This format has following form:
    * <P><code>[C][A][S][M]-<em>identifier</em></code>
    * <p>Where:
    * <UL>
    * <LI> <code>C</code> stands for the Control key
    * <LI> <code>A</code> stands for the Alt key
    * <LI> <code>S</code> stands for the Shift key
    * <LI> <code>M</code> stands for the Meta key
    * </UL>
    * Every modifier before the hyphen must be pressed.
    * <em>identifier</EM> can be any text constant from {@link KeyEvent} but
    * without the leading <code>VK_</code> characters. So {@link KeyEvent#VK_ENTER} is described as
    * <code>ENTER</code>.
    *
    * @param s the string with the description of the key
    * @return key description object, or <code>null</code> if the string does not represent any valid key
    */
    public static KeyStroke stringToKey(String s) {
        StringTokenizer st = new StringTokenizer(s.toUpperCase(), "-", true); // NOI18N

        int needed = 0;

        HashMap names = initNameAndValues()[0];

        int lastModif = -1;
        try {
            for (;;) {
                String el = st.nextToken();
                // required key
                if (el.equals("-")) { // NOI18N
                    if (lastModif != -1) {
                        needed |= lastModif;
                        lastModif = -1;
                    }
                    continue;
                }
                // if there is more elements
                if (st.hasMoreElements()) {
                    // the text should describe modifiers
                    lastModif = readModifiers(el);
                } else {
                    // last text must be the key code
                    Integer i = (Integer) names.get(el);
                    if (i != null) {
                        return KeyStroke.getKeyStroke(i.intValue(), needed);
                    } else {
                        return null;
                    }
                }
            }
        } catch (NoSuchElementException ex) {
            return null;
        }
    }

    /** Initialization of the names and values
    * @return array of two hashmaps first maps 
    *   allowed key names to their values (String, Integer) 
    *  and second     
    * hashtable for mapping of values to their names (Integer, String)
    */
    private static synchronized HashMap[] initNameAndValues() {
        if (namesAndValues != null) {
            HashMap[] arr = (HashMap[]) namesAndValues.get();
            if (arr != null) {
                return arr;
            }
        }

        Field[] fields = KeyEvent.class.getDeclaredFields();

        HashMap names = new HashMap(fields.length * 4 / 3 + 1, 0.75f);
        HashMap values = new HashMap(fields.length * 4 / 3 + 1, 0.75f);

        for (int i = 0; i < fields.length; i++) {
            if (Modifier.isStatic(fields[i].getModifiers())) {
                String name = fields[i].getName();
                if (name.startsWith("VK_")) { // NOI18N
                    // exclude VK
                    name = name.substring(3);
                    try {
                        int numb = fields[i].getInt(null);
                        Integer value = new Integer(numb);
                        names.put(name, value);
                        values.put(value, name);
                    } catch (IllegalArgumentException ex) {
                    } catch (IllegalAccessException ex) {
                    }
                }
            }
        }

        HashMap[] arr = { names, values };

        namesAndValues = new SoftReference(arr);

        return arr;
    }

    /** Reads for modifiers and creates integer with required mask.
    * @param s string with modifiers
    * @return integer with mask
    * @exception NoSuchElementException if some letter is not modifier
    */
    private static int readModifiers(String s) throws NoSuchElementException {
        int m = 0;
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
            case 'C':
                m |= KeyEvent.CTRL_MASK;
                break;
            case 'A':
                m |= KeyEvent.ALT_MASK;
                break;
            case 'M':
                m |= KeyEvent.META_MASK;
                break;
            case 'S':
                m |= KeyEvent.SHIFT_MASK;
                break;
            default:
                throw new NoSuchElementException();
            }
        }
        return m;
    }
}

Related

  1. setUseStandardFocusTraversalKeys(Component comp, boolean use)
  2. simulateEnterKey(Component c)
  3. simulateEnterKeyPressed(final Component component, final int delayInMilliseconds)
  4. simulateKeyStrokes(Component comp, String text)
  5. stringify(KeyStroke keyStroke)
  6. stringToKeys(String s)
  7. translate(KeyStroke keyStroke, Locale locale)
  8. validarNumeroInteiro(KeyEvent evt)