Java/Event/Key Event

Материал из Java эксперт
Версия от 05:58, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Activating a Keystroke When Any Child Component Has Focus

    

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton();
    MyAction action = new MyAction();
    component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
        KeyStroke.getKeyStroke("F2"), action.getValue(Action.NAME));
  }
}
class MyAction extends AbstractAction {
  public MyAction() {
    super("my action");
  }
  public void actionPerformed(ActionEvent e) {
    System.out.println("hi");
  }
}





Activating a Keystroke When Any Component in the Window Has Focus

    
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton();
    MyAction action = new MyAction();
    component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
        action.getValue(Action.NAME));
  }
}
class MyAction extends AbstractAction {
  public MyAction() {
    super("my action");
  }
  public void actionPerformed(ActionEvent e) {
    System.out.println("hi");
  }
}





Construct a new key description from a given universal string description

  
/*
 * $Id: Utilities.java,v 1.11 2008/10/14 22:31:46 rah003 Exp $
 *
 * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.awt.ruponent;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
/**
 * Contribution from NetBeans: Issue #319-swingx.
 * <p>
 * 
 * PENDING: need to reconcile with OS, JVM... added as-is because needed the
 * shortcut handling to fix #
 * 
 * @author apple
 */
public class Utilities {
    private Utilities() {
    }
    
    private static final int CTRL_WILDCARD_MASK = 32768;
    private static final int ALT_WILDCARD_MASK = CTRL_WILDCARD_MASK * 2;
    
    /** Operating system is Windows NT. */
    public static final int OS_WINNT = 1 << 0;
    /** Operating system is Windows 95. */
    public static final int OS_WIN95 = OS_WINNT << 1;
    /** Operating system is Windows 98. */
    public static final int OS_WIN98 = OS_WIN95 << 1;
    /** Operating system is Solaris. */
    public static final int OS_SOLARIS = OS_WIN98 << 1;
    /** Operating system is Linux. */
    public static final int OS_LINUX = OS_SOLARIS << 1;
    /** Operating system is HP-UX. */
    public static final int OS_HP = OS_LINUX << 1;
    /** Operating system is IBM AIX. */
    public static final int OS_AIX = OS_HP << 1;
    /** Operating system is SGI IRIX. */
    public static final int OS_IRIX = OS_AIX << 1;
    /** Operating system is Sun OS. */
    public static final int OS_SUNOS = OS_IRIX << 1;
    /** Operating system is Compaq TRU64 Unix */
    public static final int OS_TRU64 = OS_SUNOS << 1;
    /** Operating system is OS/2. */
    public static final int OS_OS2 = OS_TRU64 << 2;
    /** Operating system is Mac. */
    public static final int OS_MAC = OS_OS2 << 1;
    /** Operating system is Windows 2000. */
    public static final int OS_WIN2000 = OS_MAC << 1;
    /** Operating system is Compaq OpenVMS */
    public static final int OS_VMS = OS_WIN2000 << 1;
    /**
     *Operating system is one of the Windows variants but we don"t know which
     *one it is
     */
    public static final int OS_WIN_OTHER = OS_VMS << 1;
    /** Operating system is unknown. */
    public static final int OS_OTHER = OS_WIN_OTHER << 1;
    /** Operating system is FreeBSD
     * @since 4.50
     */
    public static final int OS_FREEBSD = OS_OTHER << 1;
    /** A mask for Windows platforms. */
    public static final int OS_WINDOWS_MASK = OS_WINNT | OS_WIN95 | OS_WIN98 | OS_WIN2000 | OS_WIN_OTHER;
    /** A mask for Unix platforms. */
    public static final int OS_UNIX_MASK = OS_SOLARIS | OS_LINUX | OS_HP | OS_AIX | OS_IRIX | OS_SUNOS | OS_TRU64 |
        OS_MAC | OS_FREEBSD;
    /** A height of the windows"s taskbar */
    public static final int TYPICAL_WINDOWS_TASKBAR_HEIGHT = 27;
    /** A height of the Mac OS X"s menu */
    private static final int TYPICAL_MACOSX_MENU_HEIGHT = 24;
    
    private static int operatingSystem = -1;
    
    /** 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<Object> namesAndValues;
    /** Get the operating system.
    * @return one of the <code>OS_*</code> constants (such as {@link #OS_WINNT})
    */
    public static int getOperatingSystem() {
        if (operatingSystem == -1) {
            String osName = System.getProperty("os.name");
            if ("Windows NT".equals(osName)) { // NOI18N
                operatingSystem = OS_WINNT;
            } else if ("Windows 95".equals(osName)) { // NOI18N
                operatingSystem = OS_WIN95;
            } else if ("Windows 98".equals(osName)) { // NOI18N
                operatingSystem = OS_WIN98;
            } else if ("Windows 2000".equals(osName)) { // NOI18N
                operatingSystem = OS_WIN2000;
            } else if (osName.startsWith("Windows ")) { // NOI18N
                operatingSystem = OS_WIN_OTHER;
            } else if ("Solaris".equals(osName)) { // NOI18N
                operatingSystem = OS_SOLARIS;
            } else if (osName.startsWith("SunOS")) { // NOI18N
                operatingSystem = OS_SOLARIS;
            }
            // JDK 1.4 b2 defines os.name for me as "Redhat Linux" -jglick
            else if (osName.endsWith("Linux")) { // NOI18N
                operatingSystem = OS_LINUX;
            } else if ("HP-UX".equals(osName)) { // NOI18N
                operatingSystem = OS_HP;
            } else if ("AIX".equals(osName)) { // NOI18N
                operatingSystem = OS_AIX;
            } else if ("Irix".equals(osName)) { // NOI18N
                operatingSystem = OS_IRIX;
            } else if ("SunOS".equals(osName)) { // NOI18N
                operatingSystem = OS_SUNOS;
            } else if ("Digital UNIX".equals(osName)) { // NOI18N
                operatingSystem = OS_TRU64;
            } else if ("OS/2".equals(osName)) { // NOI18N
                operatingSystem = OS_OS2;
            } else if ("OpenVMS".equals(osName)) { // NOI18N
                operatingSystem = OS_VMS;
            } else if (osName.equals("Mac OS X")) { // NOI18N
                operatingSystem = OS_MAC;
            } else if (osName.startsWith("Darwin")) { // NOI18N
                operatingSystem = OS_MAC;
            } else if (osName.toLowerCase(Locale.US).startsWith("freebsd")) { // NOI18N 
                operatingSystem = OS_FREEBSD;
            } else {
                operatingSystem = OS_OTHER;
            }
        }
        return operatingSystem;
    }

    /**
     * Finds out the monitor where the user currently has the input focus.
     * This method is usually used to help the client code to figure out on
     * which monitor it should place newly created windows/frames/dialogs.
     *
     * @return the GraphicsConfiguration of the monitor which currently has the
     * input focus
     */
    private static GraphicsConfiguration getCurrentGraphicsConfiguration() {
        Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
        if (focusOwner != null) {
            Window w = SwingUtilities.getWindowAncestor(focusOwner);
            if (w != null) {
                return w.getGraphicsConfiguration();
            }
        }
        return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
    }
    /**
     * Returns the usable area of the screen where applications can place its
     * windows.  The method subtracts from the screen the area of taskbars,
     * system menus and the like.  The screen this method applies to is the one
     * which is considered current, ussually the one where the current input
     * focus is.
     *
     * @return the rectangle of the screen where one can place windows
     *
     * @since 2.5
     */
    public static Rectangle getUsableScreenBounds() {
        return getUsableScreenBounds(getCurrentGraphicsConfiguration());
    }
    /**
     * Returns the usable area of the screen where applications can place its
     * windows.  The method subtracts from the screen the area of taskbars,
     * system menus and the like.
     *
     * @param gconf the GraphicsConfiguration of the monitor
     * @return the rectangle of the screen where one can place windows
     *
     * @since 2.5
     */
    public static Rectangle getUsableScreenBounds(GraphicsConfiguration gconf) {
        if (gconf == null) {
            gconf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
        }
        Rectangle bounds = new Rectangle(gconf.getBounds());
        String str;
        str = System.getProperty("netbeans.screen.insets"); // NOI18N
        if (str != null) {
            StringTokenizer st = new StringTokenizer(str, ", "); // NOI18N
            if (st.countTokens() == 4) {
                try {
                    bounds.y = Integer.parseInt(st.nextToken());
                    bounds.x = Integer.parseInt(st.nextToken());
                    bounds.height -= (bounds.y + Integer.parseInt(st.nextToken()));
                    bounds.width -= (bounds.x + Integer.parseInt(st.nextToken()));
                } catch (NumberFormatException ex) {
                    Logger.getAnonymousLogger().log(Level.WARNING, null, ex);
                }
            }
            return bounds;
        }
        str = System.getProperty("netbeans.taskbar.height"); // NOI18N
        if (str != null) {
            bounds.height -= Integer.getInteger(str, 0).intValue();
            return bounds;
        }
        try {
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Insets insets = toolkit.getScreenInsets(gconf);
            bounds.y += insets.top;
            bounds.x += insets.left;
            bounds.height -= (insets.top + insets.bottom);
            bounds.width -= (insets.left + insets.right);
        } catch (Exception ex) {
            Logger.getAnonymousLogger().log(Level.WARNING, null, ex);
        }
        return bounds;
    }
    
    /** 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;
        // JW - fix Issue #353-swingx: play nicer inside sandbox.
        try {
            fields = KeyEvent.class.getDeclaredFields();
//           fields = KeyEvent.class.getFields();
        } catch (SecurityException e) { 
            // JW: need to do better? What are the use-cases where we don"t have
            // any access to the fields?
            fields = new Field[0];
        }
        HashMap<String,Integer> names = new HashMap<String,Integer>(((fields.length * 4) / 3) + 5, 0.75f);
        HashMap<Integer,String> values = new HashMap<Integer,String>(((fields.length * 4) / 3) + 5, 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) {
                    }
                }
            }
        }
        if (names.get("CONTEXT_MENU") == null) { // NOI18N
            Integer n = new Integer(0x20C);
            names.put("CONTEXT_MENU", n); // NOI18N
            values.put(n, "CONTEXT_MENU"); // NOI18N
            n = new Integer(0x20D);
            names.put("WINDOWS", n); // NOI18N
            values.put(n, "WINDOWS"); // NOI18N
        }
        HashMap[] arr = { names, values };
        namesAndValues = new SoftReference<Object>(arr);
        return arr;
    }
    /** Converts a Swing key stroke descriptor to a familiar Emacs-like name.
    * @param stroke key description
    * @return name of the key (e.g. <code>CS-F1</code> for control-shift-function key one)
    * @see #stringToKey
    */
    public static String keyToString(KeyStroke stroke) {
        StringBuffer sb = new StringBuffer();
        // add modifiers that must be pressed
        if (addModifiers(sb, stroke.getModifiers())) {
            sb.append("-");
        }
        HashMap[] namesAndValues = initNameAndValues();
        String c = (String) namesAndValues[1].get(new Integer(stroke.getKeyCode()));
        if (c == null) {
            sb.append(stroke.getKeyChar());
        } else {
            sb.append(c);
        }
        return sb.toString();
    }
    /** 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>
    * The format also supports two wildcard codes, to support differences in
    * platforms.  These are the preferred choices for registering keystrokes,
    * since platform conflicts will automatically be handled:
    * <UL>
    * <LI> <code>D</code> stands for the default menu accelerator - the Control
    *  key on most platforms, the Command (meta) key on Macintosh</LI>
    * <LI> <code>O</code> stands for the alternate accelerator - the Alt key on
    *  most platforms, the Ctrl key on Macintosh (Macintosh uses Alt as a
    *  secondary shift key for composing international characters - if you bind
    *  Alt-8 to an action, a mac user with a French keyboard will not be able
    *  to type the <code>[</code> character, which is a significant handicap</LI>
    * </UL>
    * If you use the wildcard characters, and specify a key which will conflict
    * with keys the operating system consumes, it will be mapped to whichever
    * choice can work - for example, on Macintosh, Command-Q is always consumed
    * by the operating system, so <code>D-Q</code> will always map to Control-Q.
    * <p>
    * 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(Locale.ENGLISH), "-", 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);
                    boolean wildcard = (needed & CTRL_WILDCARD_MASK) != 0;
                    //Strip out the explicit mask - KeyStroke won"t know
                    //what to do with it
                    needed = needed & ~CTRL_WILDCARD_MASK;
                    boolean macAlt = (needed & ALT_WILDCARD_MASK) != 0;
                    needed = needed & ~ALT_WILDCARD_MASK;
                    if (i != null) {
                        //#26854 - Default accelerator should be Command on mac
                        if (wildcard) {
                            needed |= getMenuShortCutKeyMask();
                            if ((getOperatingSystem() & OS_MAC) != 0) {
                                if (!usableKeyOnMac(i.intValue(), needed)) {
                                    needed &= ~getMenuShortCutKeyMask();
                                    needed |= KeyEvent.CTRL_MASK;
                                }
                            }
                        }
                        if (macAlt) {
                            if (getOperatingSystem() == OS_MAC) {
                                needed |= KeyEvent.CTRL_MASK;
                            } else {
                                needed |= KeyEvent.ALT_MASK;
                            }
                        }
                        return KeyStroke.getKeyStroke(i.intValue(), needed);
                    } else {
                        return null;
                    }
                }
            }
        } catch (NoSuchElementException ex) {
            return null;
        }
    }
    /**
     * need to guard against headlessExceptions when testing.
     * @return the acceletor mask for shortcuts.
     */
    private static int getMenuShortCutKeyMask() {
        if (GraphicsEnvironment.isHeadless()) {
            return ((getOperatingSystem() & OS_MAC) != 0) ? 
                    KeyEvent.META_MASK : KeyEvent.CTRL_MASK;
        }
 
        return Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    }
    private static boolean usableKeyOnMac(int key, int mask) {
        //All permutations fail for Q except ctrl
        if (key == KeyEvent.VK_Q) {
            return false;
        }
        boolean isMeta = ((mask & KeyEvent.META_MASK) != 0) || ((mask & KeyEvent.CTRL_DOWN_MASK) != 0);
        boolean isAlt = ((mask & KeyEvent.ALT_MASK) != 0) || ((mask & KeyEvent.ALT_DOWN_MASK) != 0);
        boolean isOnlyMeta = isMeta && ((mask & ~(KeyEvent.META_DOWN_MASK | KeyEvent.META_MASK)) == 0);
        //Mac OS consumes keys Command+ these keys - the app will never see
        //them, so CTRL should not be remapped for these
        if (isOnlyMeta) {
            return (key != KeyEvent.VK_H) && (key != KeyEvent.VK_SPACE) && (key != KeyEvent.VK_TAB);
        } else return !((key == KeyEvent.VK_D) && isMeta && isAlt);
    }
    /** Convert a space-separated list of Emacs-like key binding names to a list of Swing key strokes.
    * @param s the string with keys
    * @return array of key strokes, or <code>null</code> if the string description is not valid
    * @see #stringToKey
    */
    public static KeyStroke[] stringToKeys(String s) {
        StringTokenizer st = new StringTokenizer(s.toUpperCase(Locale.ENGLISH), " "); // NOI18N
        ArrayList<KeyStroke> arr = new ArrayList<KeyStroke>();
        while (st.hasMoreElements()) {
            s = st.nextToken();
            KeyStroke k = stringToKey(s);
            if (k == null) {
                return null;
            }
            arr.add(k);
        }
        return arr.toArray(new KeyStroke[arr.size()]);
    }
    /** Adds characters for modifiers to the buffer.
    * @param buf buffer to add to
    * @param modif modifiers to add (KeyEvent.XXX_MASK)
    * @return true if something has been added
    */
    private static boolean addModifiers(StringBuffer buf, int modif) {
        boolean b = false;
        if ((modif & KeyEvent.CTRL_MASK) != 0) {
            buf.append("C"); // NOI18N
            b = true;
        }
        if ((modif & KeyEvent.ALT_MASK) != 0) {
            buf.append("A"); // NOI18N
            b = true;
        }
        if ((modif & KeyEvent.SHIFT_MASK) != 0) {
            buf.append("S"); // NOI18N
            b = true;
        }
        if ((modif & KeyEvent.META_MASK) != 0) {
            buf.append("M"); // NOI18N
            b = true;
        }
        if ((modif & CTRL_WILDCARD_MASK) != 0) {
            buf.append("D");
            b = true;
        }
        if ((modif & ALT_WILDCARD_MASK) != 0) {
            buf.append("O");
            b = true;
        }
        return b;
    }
    /** 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;
            case "D":
                m |= CTRL_WILDCARD_MASK;
                break;
            case "O":
                m |= ALT_WILDCARD_MASK;
                break;
            default:
                throw new NoSuchElementException(s);
            }
        }
        return m;
    }
    
    
}





Converting a KeyStroke to a String

    
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton("button");
    InputMap map = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    list(map, map.keys());
    list(map, map.allKeys());
  }
  static void list(InputMap map, KeyStroke[] keys) {
    if (keys == null) {
      return;
    }
    for (int i = 0; i < keys.length; i++) {
      keyStroke2String(keys[i]);
      while (map.get(keys[i]) == null) {
        map = map.getParent();
      }
      if (map.get(keys[i]) instanceof String) {
        String actionName = (String) map.get(keys[i]);
      } else {
        Action action = (Action) map.get(keys[i]);
      }
    }
  }
  static void keyStroke2String(KeyStroke key) {
    int m = key.getModifiers();
    if ((m & (InputEvent.SHIFT_DOWN_MASK | InputEvent.SHIFT_MASK)) != 0) {
      System.out.println("shift ");
    }
    if ((m & (InputEvent.CTRL_DOWN_MASK | InputEvent.CTRL_MASK)) != 0) {
      System.out.println("ctrl ");
    }
    if ((m & (InputEvent.META_DOWN_MASK | InputEvent.META_MASK)) != 0) {
      System.out.println("meta ");
    }
    if ((m & (InputEvent.ALT_DOWN_MASK | InputEvent.ALT_MASK)) != 0) {
      System.out.println("alt ");
    }
    if ((m & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON1_MASK)) != 0) {
      System.out.println("button1 ");
    }
    if ((m & (InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON2_MASK)) != 0) {
      System.out.println("button2 ");
    }
    if ((m & (InputEvent.BUTTON3_DOWN_MASK | InputEvent.BUTTON3_MASK)) != 0) {
      System.out.println("button3 ");
    }
    switch (key.getKeyEventType()) {
    case KeyEvent.KEY_TYPED:
      System.out.println("typed ");
      System.out.println(key.getKeyChar() + " ");
      break;
    case KeyEvent.KEY_PRESSED:
      System.out.println("pressed ");
      System.out.println(getKeyText(key.getKeyCode()) + " ");
      break;
    case KeyEvent.KEY_RELEASED:
      System.out.println("released ");
      System.out.println(getKeyText(key.getKeyCode()) + " ");
      break;
    default:
      System.out.println("unknown-event-type ");
      break;
    }
  }
  static String getKeyText(int keyCode) {
    if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9 || keyCode >= KeyEvent.VK_A
        && keyCode <= KeyEvent.VK_Z) {
      return String.valueOf((char) keyCode);
    }
    switch (keyCode) {
    case KeyEvent.VK_COMMA:
      return "COMMA";
    case KeyEvent.VK_PERIOD:
      return "PERIOD";
    case KeyEvent.VK_SLASH:
      return "SLASH";
    case KeyEvent.VK_SEMICOLON:
      return "SEMICOLON";
    case KeyEvent.VK_EQUALS:
      return "EQUALS";
    case KeyEvent.VK_OPEN_BRACKET:
      return "OPEN_BRACKET";
    case KeyEvent.VK_BACK_SLASH:
      return "BACK_SLASH";
    case KeyEvent.VK_CLOSE_BRACKET:
      return "CLOSE_BRACKET";
    case KeyEvent.VK_ENTER:
      return "ENTER";
    case KeyEvent.VK_BACK_SPACE:
      return "BACK_SPACE";
    case KeyEvent.VK_TAB:
      return "TAB";
    case KeyEvent.VK_CANCEL:
      return "CANCEL";
    case KeyEvent.VK_CLEAR:
      return "CLEAR";
    case KeyEvent.VK_SHIFT:
      return "SHIFT";
    case KeyEvent.VK_CONTROL:
      return "CONTROL";
    case KeyEvent.VK_ALT:
      return "ALT";
    case KeyEvent.VK_PAUSE:
      return "PAUSE";
    case KeyEvent.VK_CAPS_LOCK:
      return "CAPS_LOCK";
    case KeyEvent.VK_ESCAPE:
      return "ESCAPE";
    case KeyEvent.VK_SPACE:
      return "SPACE";
    case KeyEvent.VK_PAGE_UP:
      return "PAGE_UP";
    case KeyEvent.VK_PAGE_DOWN:
      return "PAGE_DOWN";
    case KeyEvent.VK_END:
      return "END";
    case KeyEvent.VK_HOME:
      return "HOME";
    case KeyEvent.VK_LEFT:
      return "LEFT";
    case KeyEvent.VK_UP:
      return "UP";
    case KeyEvent.VK_RIGHT:
      return "RIGHT";
    case KeyEvent.VK_DOWN:
      return "DOWN";
    case KeyEvent.VK_MULTIPLY:
      return "MULTIPLY";
    case KeyEvent.VK_ADD:
      return "ADD";
    case KeyEvent.VK_SEPARATOR:
      return "SEPARATOR";
    case KeyEvent.VK_SUBTRACT:
      return "SUBTRACT";
    case KeyEvent.VK_DECIMAL:
      return "DECIMAL";
    case KeyEvent.VK_DIVIDE:
      return "DIVIDE";
    case KeyEvent.VK_DELETE:
      return "DELETE";
    case KeyEvent.VK_NUM_LOCK:
      return "NUM_LOCK";
    case KeyEvent.VK_SCROLL_LOCK:
      return "SCROLL_LOCK";
    case KeyEvent.VK_F1:
      return "F1";
    case KeyEvent.VK_F2:
      return "F2";
    case KeyEvent.VK_F3:
      return "F3";
    case KeyEvent.VK_F4:
      return "F4";
    case KeyEvent.VK_F5:
      return "F5";
    case KeyEvent.VK_F6:
      return "F6";
    case KeyEvent.VK_F7:
      return "F7";
    case KeyEvent.VK_F8:
      return "F8";
    case KeyEvent.VK_F9:
      return "F9";
    case KeyEvent.VK_F10:
      return "F10";
    case KeyEvent.VK_F11:
      return "F11";
    case KeyEvent.VK_F12:
      return "F12";
    case KeyEvent.VK_F13:
      return "F13";
    case KeyEvent.VK_F14:
      return "F14";
    case KeyEvent.VK_F15:
      return "F15";
    case KeyEvent.VK_F16:
      return "F16";
    case KeyEvent.VK_F17:
      return "F17";
    case KeyEvent.VK_F18:
      return "F18";
    case KeyEvent.VK_F19:
      return "F19";
    case KeyEvent.VK_F20:
      return "F20";
    case KeyEvent.VK_F21:
      return "F21";
    case KeyEvent.VK_F22:
      return "F22";
    case KeyEvent.VK_F23:
      return "F23";
    case KeyEvent.VK_F24:
      return "F24";
    case KeyEvent.VK_PRINTSCREEN:
      return "PRINTSCREEN";
    case KeyEvent.VK_INSERT:
      return "INSERT";
    case KeyEvent.VK_HELP:
      return "HELP";
    case KeyEvent.VK_META:
      return "META";
    case KeyEvent.VK_BACK_QUOTE:
      return "BACK_QUOTE";
    case KeyEvent.VK_QUOTE:
      return "QUOTE";
    case KeyEvent.VK_KP_UP:
      return "KP_UP";
    case KeyEvent.VK_KP_DOWN:
      return "KP_DOWN";
    case KeyEvent.VK_KP_LEFT:
      return "KP_LEFT";
    case KeyEvent.VK_KP_RIGHT:
      return "KP_RIGHT";
    case KeyEvent.VK_DEAD_GRAVE:
      return "DEAD_GRAVE";
    case KeyEvent.VK_DEAD_ACUTE:
      return "DEAD_ACUTE";
    case KeyEvent.VK_DEAD_CIRCUMFLEX:
      return "DEAD_CIRCUMFLEX";
    case KeyEvent.VK_DEAD_TILDE:
      return "DEAD_TILDE";
    case KeyEvent.VK_DEAD_MACRON:
      return "DEAD_MACRON";
    case KeyEvent.VK_DEAD_BREVE:
      return "DEAD_BREVE";
    case KeyEvent.VK_DEAD_ABOVEDOT:
      return "DEAD_ABOVEDOT";
    case KeyEvent.VK_DEAD_DIAERESIS:
      return "DEAD_DIAERESIS";
    case KeyEvent.VK_DEAD_ABOVERING:
      return "DEAD_ABOVERING";
    case KeyEvent.VK_DEAD_DOUBLEACUTE:
      return "DEAD_DOUBLEACUTE";
    case KeyEvent.VK_DEAD_CARON:
      return "DEAD_CARON";
    case KeyEvent.VK_DEAD_CEDILLA:
      return "DEAD_CEDILLA";
    case KeyEvent.VK_DEAD_OGONEK:
      return "DEAD_OGONEK";
    case KeyEvent.VK_DEAD_IOTA:
      return "DEAD_IOTA";
    case KeyEvent.VK_DEAD_VOICED_SOUND:
      return "DEAD_VOICED_SOUND";
    case KeyEvent.VK_DEAD_SEMIVOICED_SOUND:
      return "DEAD_SEMIVOICED_SOUND";
    case KeyEvent.VK_AMPERSAND:
      return "AMPERSAND";
    case KeyEvent.VK_ASTERISK:
      return "ASTERISK";
    case KeyEvent.VK_QUOTEDBL:
      return "QUOTEDBL";
    case KeyEvent.VK_LESS:
      return "LESS";
    case KeyEvent.VK_GREATER:
      return "GREATER";
    case KeyEvent.VK_BRACELEFT:
      return "BRACELEFT";
    case KeyEvent.VK_BRACERIGHT:
      return "BRACERIGHT";
    case KeyEvent.VK_AT:
      return "AT";
    case KeyEvent.VK_COLON:
      return "COLON";
    case KeyEvent.VK_CIRCUMFLEX:
      return "CIRCUMFLEX";
    case KeyEvent.VK_DOLLAR:
      return "DOLLAR";
    case KeyEvent.VK_EURO_SIGN:
      return "EURO_SIGN";
    case KeyEvent.VK_EXCLAMATION_MARK:
      return "EXCLAMATION_MARK";
    case KeyEvent.VK_INVERTED_EXCLAMATION_MARK:
      return "INVERTED_EXCLAMATION_MARK";
    case KeyEvent.VK_LEFT_PARENTHESIS:
      return "LEFT_PARENTHESIS";
    case KeyEvent.VK_NUMBER_SIGN:
      return "NUMBER_SIGN";
    case KeyEvent.VK_MINUS:
      return "MINUS";
    case KeyEvent.VK_PLUS:
      return "PLUS";
    case KeyEvent.VK_RIGHT_PARENTHESIS:
      return "RIGHT_PARENTHESIS";
    case KeyEvent.VK_UNDERSCORE:
      return "UNDERSCORE";
    case KeyEvent.VK_FINAL:
      return "FINAL";
    case KeyEvent.VK_CONVERT:
      return "CONVERT";
    case KeyEvent.VK_NONCONVERT:
      return "NONCONVERT";
    case KeyEvent.VK_ACCEPT:
      return "ACCEPT";
    case KeyEvent.VK_MODECHANGE:
      return "MODECHANGE";
    case KeyEvent.VK_KANA:
      return "KANA";
    case KeyEvent.VK_KANJI:
      return "KANJI";
    case KeyEvent.VK_ALPHANUMERIC:
      return "ALPHANUMERIC";
    case KeyEvent.VK_KATAKANA:
      return "KATAKANA";
    case KeyEvent.VK_HIRAGANA:
      return "HIRAGANA";
    case KeyEvent.VK_FULL_WIDTH:
      return "FULL_WIDTH";
    case KeyEvent.VK_HALF_WIDTH:
      return "HALF_WIDTH";
    case KeyEvent.VK_ROMAN_CHARACTERS:
      return "ROMAN_CHARACTERS";
    case KeyEvent.VK_ALL_CANDIDATES:
      return "ALL_CANDIDATES";
    case KeyEvent.VK_PREVIOUS_CANDIDATE:
      return "PREVIOUS_CANDIDATE";
    case KeyEvent.VK_CODE_INPUT:
      return "CODE_INPUT";
    case KeyEvent.VK_JAPANESE_KATAKANA:
      return "JAPANESE_KATAKANA";
    case KeyEvent.VK_JAPANESE_HIRAGANA:
      return "JAPANESE_HIRAGANA";
    case KeyEvent.VK_JAPANESE_ROMAN:
      return "JAPANESE_ROMAN";
    case KeyEvent.VK_KANA_LOCK:
      return "KANA_LOCK";
    case KeyEvent.VK_INPUT_METHOD_ON_OFF:
      return "INPUT_METHOD_ON_OFF";
    case KeyEvent.VK_AGAIN:
      return "AGAIN";
    case KeyEvent.VK_UNDO:
      return "UNDO";
    case KeyEvent.VK_COPY:
      return "COPY";
    case KeyEvent.VK_PASTE:
      return "PASTE";
    case KeyEvent.VK_CUT:
      return "CUT";
    case KeyEvent.VK_FIND:
      return "FIND";
    case KeyEvent.VK_PROPS:
      return "PROPS";
    case KeyEvent.VK_STOP:
      return "STOP";
    case KeyEvent.VK_COMPOSE:
      return "COMPOSE";
    case KeyEvent.VK_ALT_GRAPH:
      return "ALT_GRAPH";
    }
    if (keyCode >= KeyEvent.VK_NUMPAD0 && keyCode <= KeyEvent.VK_NUMPAD9) {
      char c = (char) (keyCode - KeyEvent.VK_NUMPAD0 + "0");
      return "NUMPAD" + c;
    }
    return "unknown(0x" + Integer.toString(keyCode, 16) + ")";
  }
}





Creating a KeyStroke and Binding It to an Action

    
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton("Button");
    component.getInputMap().put(KeyStroke.getKeyStroke("F2"), "actionName");
    component.getInputMap().put(KeyStroke.getKeyStroke("control A"), "actionName");
    component.getInputMap().put(KeyStroke.getKeyStroke("shift F2"), "actionName");
    component.getInputMap().put(KeyStroke.getKeyStroke("("), "actionName");
    component.getInputMap().put(KeyStroke.getKeyStroke("button3 F"), "actionName");
    component.getInputMap().put(KeyStroke.getKeyStroke("typed x"), "actionName");
    component.getInputMap().put(KeyStroke.getKeyStroke("released DELETE"), "actionName");
    component.getInputMap().put(KeyStroke.getKeyStroke("shift UP"), "actionName");
    component.getActionMap().put("actionName", new AbstractAction("actionName") {
      public void actionPerformed(ActionEvent evt) {
        System.out.println(evt);
      }
    });
  }
}





Get key pressed as a key character (which is a Unicode character)

    
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {
    if (evt.getKeyChar() == "a") {
      System.out.println("Check for key characters: " + evt.getKeyChar());
    }
    if (evt.getKeyCode() == KeyEvent.VK_HOME) {
      System.out.println("Check for key codes: " + evt.getKeyCode());
    }
  }
}





Get key pressed as a key code

    
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {
    if (evt.getKeyChar() == "a") {
      System.out.println("Check for key characters: " + evt.getKeyChar());
    }
    if (evt.getKeyCode() == KeyEvent.VK_HOME) {
      System.out.println("Check for key codes: " + evt.getKeyCode());
    }
  }
}





Get Key Text

    
/*
 * Copyright 2000,2005 wingS development team.
 *
 * This file is part of wingS (http://wingsframework.org).
 *
 * wingS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 *
 * Please see COPYING for the complete licence.
 */

import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.KeyStroke;
/**
 * This source code was taken from a code example at http://javaalmanac.ru/
 * and slightly altered to fit our purpose.
 * @author ole
 *
 */
public class KeystrokeUtil {
    public static String keyStroke2String(KeyStroke key) {
        if (key == null) return "";
        StringBuilder s = new StringBuilder(50);
        int m = key.getModifiers();
        if ((m & (InputEvent.CTRL_DOWN_MASK|InputEvent.CTRL_MASK)) != 0) {
            s.append("Ctrl+");
        }
        if ((m & (InputEvent.META_DOWN_MASK|InputEvent.META_MASK)) != 0) {
            s.append("Meta+");
        }
        if ((m & (InputEvent.ALT_DOWN_MASK|InputEvent.ALT_MASK)) != 0) {
            s.append("Alt+");
        }
        if ((m & (InputEvent.SHIFT_DOWN_MASK|InputEvent.SHIFT_MASK)) != 0) {
            s.append("Shift+");
        }
        if ((m & (InputEvent.BUTTON1_DOWN_MASK|InputEvent.BUTTON1_MASK)) != 0) {
            s.append("Button1+");
        }
        if ((m & (InputEvent.BUTTON2_DOWN_MASK|InputEvent.BUTTON2_MASK)) != 0) {
            s.append("Button2+");
        }
        if ((m & (InputEvent.BUTTON3_DOWN_MASK|InputEvent.BUTTON3_MASK)) != 0) {
            s.append("Button3+");
        }
        switch (key.getKeyEventType()) {
        case KeyEvent.KEY_TYPED:
            s.append(key.getKeyChar() + " ");
            break;
        case KeyEvent.KEY_PRESSED:
        case KeyEvent.KEY_RELEASED:
            s.append(getKeyText(key.getKeyCode()) + " ");
            break;
        default:
            s.append("unknown-event-type ");
            break;
        }
        return s.toString();
    }
    public static String getKeyText(int keyCode) {
        if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9 ||
            keyCode >= KeyEvent.VK_A && keyCode <= KeyEvent.VK_Z) {
            return String.valueOf((char)keyCode);
        }
        switch(keyCode) {
          case KeyEvent.VK_COMMA: return "COMMA";
          case KeyEvent.VK_PERIOD: return "PERIOD";
          case KeyEvent.VK_SLASH: return "SLASH";
          case KeyEvent.VK_SEMICOLON: return "SEMICOLON";
          case KeyEvent.VK_EQUALS: return "EQUALS";
          case KeyEvent.VK_OPEN_BRACKET: return "OPEN_BRACKET";
          case KeyEvent.VK_BACK_SLASH: return "BACK_SLASH";
          case KeyEvent.VK_CLOSE_BRACKET: return "CLOSE_BRACKET";
          case KeyEvent.VK_ENTER: return "ENTER";
          case KeyEvent.VK_BACK_SPACE: return "BACK_SPACE";
          case KeyEvent.VK_TAB: return "TAB";
          case KeyEvent.VK_CANCEL: return "CANCEL";
          case KeyEvent.VK_CLEAR: return "CLEAR";
          case KeyEvent.VK_SHIFT: return "SHIFT";
          case KeyEvent.VK_CONTROL: return "CONTROL";
          case KeyEvent.VK_ALT: return "ALT";
          case KeyEvent.VK_PAUSE: return "PAUSE";
          case KeyEvent.VK_CAPS_LOCK: return "CAPS_LOCK";
          case KeyEvent.VK_ESCAPE: return "ESCAPE";
          case KeyEvent.VK_SPACE: return "SPACE";
          case KeyEvent.VK_PAGE_UP: return "PAGE_UP";
          case KeyEvent.VK_PAGE_DOWN: return "PAGE_DOWN";
          case KeyEvent.VK_END: return "END";
          case KeyEvent.VK_HOME: return "HOME";
          case KeyEvent.VK_LEFT: return "LEFT";
          case KeyEvent.VK_UP: return "UP";
          case KeyEvent.VK_RIGHT: return "RIGHT";
          case KeyEvent.VK_DOWN: return "DOWN";
          // numpad numeric keys handled below
          case KeyEvent.VK_MULTIPLY: return "MULTIPLY";
          case KeyEvent.VK_ADD: return "ADD";
          case KeyEvent.VK_SEPARATOR: return "SEPARATOR";
          case KeyEvent.VK_SUBTRACT: return "SUBTRACT";
          case KeyEvent.VK_DECIMAL: return "DECIMAL";
          case KeyEvent.VK_DIVIDE: return "DIVIDE";
          case KeyEvent.VK_DELETE: return "DELETE";
          case KeyEvent.VK_NUM_LOCK: return "NUM_LOCK";
          case KeyEvent.VK_SCROLL_LOCK: return "SCROLL_LOCK";
          case KeyEvent.VK_F1: return "F1";
          case KeyEvent.VK_F2: return "F2";
          case KeyEvent.VK_F3: return "F3";
          case KeyEvent.VK_F4: return "F4";
          case KeyEvent.VK_F5: return "F5";
          case KeyEvent.VK_F6: return "F6";
          case KeyEvent.VK_F7: return "F7";
          case KeyEvent.VK_F8: return "F8";
          case KeyEvent.VK_F9: return "F9";
          case KeyEvent.VK_F10: return "F10";
          case KeyEvent.VK_F11: return "F11";
          case KeyEvent.VK_F12: return "F12";
          case KeyEvent.VK_F13: return "F13";
          case KeyEvent.VK_F14: return "F14";
          case KeyEvent.VK_F15: return "F15";
          case KeyEvent.VK_F16: return "F16";
          case KeyEvent.VK_F17: return "F17";
          case KeyEvent.VK_F18: return "F18";
          case KeyEvent.VK_F19: return "F19";
          case KeyEvent.VK_F20: return "F20";
          case KeyEvent.VK_F21: return "F21";
          case KeyEvent.VK_F22: return "F22";
          case KeyEvent.VK_F23: return "F23";
          case KeyEvent.VK_F24: return "F24";
          case KeyEvent.VK_PRINTSCREEN: return "PRINTSCREEN";
          case KeyEvent.VK_INSERT: return "INSERT";
          case KeyEvent.VK_HELP: return "HELP";
          case KeyEvent.VK_META: return "META";
          case KeyEvent.VK_BACK_QUOTE: return "BACK_QUOTE";
          case KeyEvent.VK_QUOTE: return "QUOTE";
          case KeyEvent.VK_KP_UP: return "KP_UP";
          case KeyEvent.VK_KP_DOWN: return "KP_DOWN";
          case KeyEvent.VK_KP_LEFT: return "KP_LEFT";
          case KeyEvent.VK_KP_RIGHT: return "KP_RIGHT";
          case KeyEvent.VK_DEAD_GRAVE: return "DEAD_GRAVE";
          case KeyEvent.VK_DEAD_ACUTE: return "DEAD_ACUTE";
          case KeyEvent.VK_DEAD_CIRCUMFLEX: return "DEAD_CIRCUMFLEX";
          case KeyEvent.VK_DEAD_TILDE: return "DEAD_TILDE";
          case KeyEvent.VK_DEAD_MACRON: return "DEAD_MACRON";
          case KeyEvent.VK_DEAD_BREVE: return "DEAD_BREVE";
          case KeyEvent.VK_DEAD_ABOVEDOT: return "DEAD_ABOVEDOT";
          case KeyEvent.VK_DEAD_DIAERESIS: return "DEAD_DIAERESIS";
          case KeyEvent.VK_DEAD_ABOVERING: return "DEAD_ABOVERING";
          case KeyEvent.VK_DEAD_DOUBLEACUTE: return "DEAD_DOUBLEACUTE";
          case KeyEvent.VK_DEAD_CARON: return "DEAD_CARON";
          case KeyEvent.VK_DEAD_CEDILLA: return "DEAD_CEDILLA";
          case KeyEvent.VK_DEAD_OGONEK: return "DEAD_OGONEK";
          case KeyEvent.VK_DEAD_IOTA: return "DEAD_IOTA";
          case KeyEvent.VK_DEAD_VOICED_SOUND: return "DEAD_VOICED_SOUND";
          case KeyEvent.VK_DEAD_SEMIVOICED_SOUND: return "DEAD_SEMIVOICED_SOUND";
          case KeyEvent.VK_AMPERSAND: return "AMPERSAND";
          case KeyEvent.VK_ASTERISK: return "ASTERISK";
          case KeyEvent.VK_QUOTEDBL: return "QUOTEDBL";
          case KeyEvent.VK_LESS: return "LESS";
          case KeyEvent.VK_GREATER: return "GREATER";
          case KeyEvent.VK_BRACELEFT: return "BRACELEFT";
          case KeyEvent.VK_BRACERIGHT: return "BRACERIGHT";
          case KeyEvent.VK_AT: return "AT";
          case KeyEvent.VK_COLON: return "COLON";
          case KeyEvent.VK_CIRCUMFLEX: return "CIRCUMFLEX";
          case KeyEvent.VK_DOLLAR: return "DOLLAR";
          case KeyEvent.VK_EURO_SIGN: return "EURO_SIGN";
          case KeyEvent.VK_EXCLAMATION_MARK: return "EXCLAMATION_MARK";
          case KeyEvent.VK_INVERTED_EXCLAMATION_MARK:
                   return "INVERTED_EXCLAMATION_MARK";
          case KeyEvent.VK_LEFT_PARENTHESIS: return "LEFT_PARENTHESIS";
          case KeyEvent.VK_NUMBER_SIGN: return "NUMBER_SIGN";
          case KeyEvent.VK_MINUS: return "MINUS";
          case KeyEvent.VK_PLUS: return "PLUS";
          case KeyEvent.VK_RIGHT_PARENTHESIS: return "RIGHT_PARENTHESIS";
          case KeyEvent.VK_UNDERSCORE: return "UNDERSCORE";
          case KeyEvent.VK_FINAL: return "FINAL";
          case KeyEvent.VK_CONVERT: return "CONVERT";
          case KeyEvent.VK_NONCONVERT: return "NONCONVERT";
          case KeyEvent.VK_ACCEPT: return "ACCEPT";
          case KeyEvent.VK_MODECHANGE: return "MODECHANGE";
          case KeyEvent.VK_KANA: return "KANA";
          case KeyEvent.VK_KANJI: return "KANJI";
          case KeyEvent.VK_ALPHANUMERIC: return "ALPHANUMERIC";
          case KeyEvent.VK_KATAKANA: return "KATAKANA";
          case KeyEvent.VK_HIRAGANA: return "HIRAGANA";
          case KeyEvent.VK_FULL_WIDTH: return "FULL_WIDTH";
          case KeyEvent.VK_HALF_WIDTH: return "HALF_WIDTH";
          case KeyEvent.VK_ROMAN_CHARACTERS: return "ROMAN_CHARACTERS";
          case KeyEvent.VK_ALL_CANDIDATES: return "ALL_CANDIDATES";
          case KeyEvent.VK_PREVIOUS_CANDIDATE: return "PREVIOUS_CANDIDATE";
          case KeyEvent.VK_CODE_INPUT: return "CODE_INPUT";
          case KeyEvent.VK_JAPANESE_KATAKANA: return "JAPANESE_KATAKANA";
          case KeyEvent.VK_JAPANESE_HIRAGANA: return "JAPANESE_HIRAGANA";
          case KeyEvent.VK_JAPANESE_ROMAN: return "JAPANESE_ROMAN";
          case KeyEvent.VK_KANA_LOCK: return "KANA_LOCK";
          case KeyEvent.VK_INPUT_METHOD_ON_OFF: return "INPUT_METHOD_ON_OFF";
          case KeyEvent.VK_AGAIN: return "AGAIN";
          case KeyEvent.VK_UNDO: return "UNDO";
          case KeyEvent.VK_COPY: return "COPY";
          case KeyEvent.VK_PASTE: return "PASTE";
          case KeyEvent.VK_CUT: return "CUT";
          case KeyEvent.VK_FIND: return "FIND";
          case KeyEvent.VK_PROPS: return "PROPS";
          case KeyEvent.VK_STOP: return "STOP";
          case KeyEvent.VK_COMPOSE: return "COMPOSE";
          case KeyEvent.VK_ALT_GRAPH: return "ALT_GRAPH";
        }
        if (keyCode >= KeyEvent.VK_NUMPAD0 && keyCode <= KeyEvent.VK_NUMPAD9) {
            char c = (char)(keyCode - KeyEvent.VK_NUMPAD0 + "0");
            return "NUMPAD"+c;
        }
        return "unknown(0x" + Integer.toString(keyCode, 16) + ")";
    }
}





Handling Key Presses

    
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {
    if (evt.getKeyChar() == "a") {
      System.out.println("Check for key characters: " + evt.getKeyChar());
    }
    if (evt.getKeyCode() == KeyEvent.VK_HOME) {
      System.out.println("Check for key codes: " + evt.getKeyCode());
    }
  }
}





InputMap javax.swing.JComponent.getInputMap(int condition)

    
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton();
    MyAction action = new MyAction();
    component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
        action.getValue(Action.NAME));
  }
}
class MyAction extends AbstractAction {
  public MyAction() {
    super("my action");
  }
  public void actionPerformed(ActionEvent e) {
    System.out.println("hi");
  }
}





Key Event Demo

    
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * KeyEventDemo.java is a 1.4 example that requires no other files.
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class KeyEventDemo extends JPanel implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = "\n";
  public KeyEventDemo() {
    super(new BorderLayout());
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    //Uncomment this if you wish to turn off focus
    //traversal. The focus subsystem consumes
    //focus traversal keys, such as Tab and Shift Tab.
    //If you uncomment the following line of code, this
    //disables focus traversal and the Tab events will
    //become available to the key event listener.
    //typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    add(typingArea, BorderLayout.PAGE_START);
    add(scrollPane, BorderLayout.CENTER);
    add(button, BorderLayout.PAGE_END);
  }
  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    //Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    //Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put
   * them in a String, the characters afterward won"t show up in the text
   * area.)
   */
  protected void displayInfo(KeyEvent e, String s) {
    String keyString, modString, tmpString, actionString, locationString;
    //You should only rely on the key char if the event
    //is a key typed event.
    int id = e.getID();
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " ("
          + KeyEvent.getKeyText(keyCode) + ")";
    }
    int modifiers = e.getModifiersEx();
    modString = "modifiers = " + modifiers;
    tmpString = KeyEvent.getModifiersExText(modifiers);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no modifiers)";
    }
    actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(s + newline + "    " + keyString + newline + "    "
        + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("KeyEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new KeyEventDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}





Key event on frame

    
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SketchPanel extends JPanel implements KeyListener {
  private Point startPoint = new Point(0, 0);
  private Point endPoint = new Point(0, 0);
  public SketchPanel() {
    addKeyListener(this);
  }
  public void keyPressed(KeyEvent evt) {
    int keyCode = evt.getKeyCode();
    int d;
    if (evt.isShiftDown())
      d = 5;
    else
      d = 1;
    if (keyCode == KeyEvent.VK_LEFT)
      add(-d, 0);
    else if (keyCode == KeyEvent.VK_RIGHT)
      add(d, 0);
    else if (keyCode == KeyEvent.VK_UP)
      add(0, -d);
    else if (keyCode == KeyEvent.VK_DOWN)
      add(0, d);
  }
  public void keyReleased(KeyEvent evt) {
  }
  public void keyTyped(KeyEvent evt) {
  }
  public boolean isFocusTraversable() {
    return true;
  }
  public void add(int dx, int dy) {
    endPoint.x += dx;
    endPoint.y += dy;
    Graphics g = getGraphics();
    g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
    g.dispose();
    startPoint.x = endPoint.x;
    startPoint.y = endPoint.y;
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Sketch");
    frame.setSize(300, 200);
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    Container contentPane = frame.getContentPane();
    contentPane.add(new SketchPanel());
    frame.show();
  }
}





KeyStroke.getKeyStroke("F2")

    
import java.awt.KeyboardFocusManager;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton("a");
    Set set = new HashSet(component
        .getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
    set.add(KeyStroke.getKeyStroke("F2"));
    component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
  }
}





KeyStroke to String

    
/*
 * Copyright 2000,2005 wingS development team.
 *
 * This file is part of wingS (http://wingsframework.org).
 *
 * wingS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 *
 * Please see COPYING for the complete licence.
 */

import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.KeyStroke;
/**
 * This source code was taken from a code example at http://javaalmanac.ru/
 * and slightly altered to fit our purpose.
 * @author ole
 *
 */
public class KeystrokeUtil {
    public static String keyStroke2String(KeyStroke key) {
        if (key == null) return "";
        StringBuilder s = new StringBuilder(50);
        int m = key.getModifiers();
        if ((m & (InputEvent.CTRL_DOWN_MASK|InputEvent.CTRL_MASK)) != 0) {
            s.append("Ctrl+");
        }
        if ((m & (InputEvent.META_DOWN_MASK|InputEvent.META_MASK)) != 0) {
            s.append("Meta+");
        }
        if ((m & (InputEvent.ALT_DOWN_MASK|InputEvent.ALT_MASK)) != 0) {
            s.append("Alt+");
        }
        if ((m & (InputEvent.SHIFT_DOWN_MASK|InputEvent.SHIFT_MASK)) != 0) {
            s.append("Shift+");
        }
        if ((m & (InputEvent.BUTTON1_DOWN_MASK|InputEvent.BUTTON1_MASK)) != 0) {
            s.append("Button1+");
        }
        if ((m & (InputEvent.BUTTON2_DOWN_MASK|InputEvent.BUTTON2_MASK)) != 0) {
            s.append("Button2+");
        }
        if ((m & (InputEvent.BUTTON3_DOWN_MASK|InputEvent.BUTTON3_MASK)) != 0) {
            s.append("Button3+");
        }
        switch (key.getKeyEventType()) {
        case KeyEvent.KEY_TYPED:
            s.append(key.getKeyChar() + " ");
            break;
        case KeyEvent.KEY_PRESSED:
        case KeyEvent.KEY_RELEASED:
            s.append(getKeyText(key.getKeyCode()) + " ");
            break;
        default:
            s.append("unknown-event-type ");
            break;
        }
        return s.toString();
    }
    public static String getKeyText(int keyCode) {
        if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9 ||
            keyCode >= KeyEvent.VK_A && keyCode <= KeyEvent.VK_Z) {
            return String.valueOf((char)keyCode);
        }
        switch(keyCode) {
          case KeyEvent.VK_COMMA: return "COMMA";
          case KeyEvent.VK_PERIOD: return "PERIOD";
          case KeyEvent.VK_SLASH: return "SLASH";
          case KeyEvent.VK_SEMICOLON: return "SEMICOLON";
          case KeyEvent.VK_EQUALS: return "EQUALS";
          case KeyEvent.VK_OPEN_BRACKET: return "OPEN_BRACKET";
          case KeyEvent.VK_BACK_SLASH: return "BACK_SLASH";
          case KeyEvent.VK_CLOSE_BRACKET: return "CLOSE_BRACKET";
          case KeyEvent.VK_ENTER: return "ENTER";
          case KeyEvent.VK_BACK_SPACE: return "BACK_SPACE";
          case KeyEvent.VK_TAB: return "TAB";
          case KeyEvent.VK_CANCEL: return "CANCEL";
          case KeyEvent.VK_CLEAR: return "CLEAR";
          case KeyEvent.VK_SHIFT: return "SHIFT";
          case KeyEvent.VK_CONTROL: return "CONTROL";
          case KeyEvent.VK_ALT: return "ALT";
          case KeyEvent.VK_PAUSE: return "PAUSE";
          case KeyEvent.VK_CAPS_LOCK: return "CAPS_LOCK";
          case KeyEvent.VK_ESCAPE: return "ESCAPE";
          case KeyEvent.VK_SPACE: return "SPACE";
          case KeyEvent.VK_PAGE_UP: return "PAGE_UP";
          case KeyEvent.VK_PAGE_DOWN: return "PAGE_DOWN";
          case KeyEvent.VK_END: return "END";
          case KeyEvent.VK_HOME: return "HOME";
          case KeyEvent.VK_LEFT: return "LEFT";
          case KeyEvent.VK_UP: return "UP";
          case KeyEvent.VK_RIGHT: return "RIGHT";
          case KeyEvent.VK_DOWN: return "DOWN";
          // numpad numeric keys handled below
          case KeyEvent.VK_MULTIPLY: return "MULTIPLY";
          case KeyEvent.VK_ADD: return "ADD";
          case KeyEvent.VK_SEPARATOR: return "SEPARATOR";
          case KeyEvent.VK_SUBTRACT: return "SUBTRACT";
          case KeyEvent.VK_DECIMAL: return "DECIMAL";
          case KeyEvent.VK_DIVIDE: return "DIVIDE";
          case KeyEvent.VK_DELETE: return "DELETE";
          case KeyEvent.VK_NUM_LOCK: return "NUM_LOCK";
          case KeyEvent.VK_SCROLL_LOCK: return "SCROLL_LOCK";
          case KeyEvent.VK_F1: return "F1";
          case KeyEvent.VK_F2: return "F2";
          case KeyEvent.VK_F3: return "F3";
          case KeyEvent.VK_F4: return "F4";
          case KeyEvent.VK_F5: return "F5";
          case KeyEvent.VK_F6: return "F6";
          case KeyEvent.VK_F7: return "F7";
          case KeyEvent.VK_F8: return "F8";
          case KeyEvent.VK_F9: return "F9";
          case KeyEvent.VK_F10: return "F10";
          case KeyEvent.VK_F11: return "F11";
          case KeyEvent.VK_F12: return "F12";
          case KeyEvent.VK_F13: return "F13";
          case KeyEvent.VK_F14: return "F14";
          case KeyEvent.VK_F15: return "F15";
          case KeyEvent.VK_F16: return "F16";
          case KeyEvent.VK_F17: return "F17";
          case KeyEvent.VK_F18: return "F18";
          case KeyEvent.VK_F19: return "F19";
          case KeyEvent.VK_F20: return "F20";
          case KeyEvent.VK_F21: return "F21";
          case KeyEvent.VK_F22: return "F22";
          case KeyEvent.VK_F23: return "F23";
          case KeyEvent.VK_F24: return "F24";
          case KeyEvent.VK_PRINTSCREEN: return "PRINTSCREEN";
          case KeyEvent.VK_INSERT: return "INSERT";
          case KeyEvent.VK_HELP: return "HELP";
          case KeyEvent.VK_META: return "META";
          case KeyEvent.VK_BACK_QUOTE: return "BACK_QUOTE";
          case KeyEvent.VK_QUOTE: return "QUOTE";
          case KeyEvent.VK_KP_UP: return "KP_UP";
          case KeyEvent.VK_KP_DOWN: return "KP_DOWN";
          case KeyEvent.VK_KP_LEFT: return "KP_LEFT";
          case KeyEvent.VK_KP_RIGHT: return "KP_RIGHT";
          case KeyEvent.VK_DEAD_GRAVE: return "DEAD_GRAVE";
          case KeyEvent.VK_DEAD_ACUTE: return "DEAD_ACUTE";
          case KeyEvent.VK_DEAD_CIRCUMFLEX: return "DEAD_CIRCUMFLEX";
          case KeyEvent.VK_DEAD_TILDE: return "DEAD_TILDE";
          case KeyEvent.VK_DEAD_MACRON: return "DEAD_MACRON";
          case KeyEvent.VK_DEAD_BREVE: return "DEAD_BREVE";
          case KeyEvent.VK_DEAD_ABOVEDOT: return "DEAD_ABOVEDOT";
          case KeyEvent.VK_DEAD_DIAERESIS: return "DEAD_DIAERESIS";
          case KeyEvent.VK_DEAD_ABOVERING: return "DEAD_ABOVERING";
          case KeyEvent.VK_DEAD_DOUBLEACUTE: return "DEAD_DOUBLEACUTE";
          case KeyEvent.VK_DEAD_CARON: return "DEAD_CARON";
          case KeyEvent.VK_DEAD_CEDILLA: return "DEAD_CEDILLA";
          case KeyEvent.VK_DEAD_OGONEK: return "DEAD_OGONEK";
          case KeyEvent.VK_DEAD_IOTA: return "DEAD_IOTA";
          case KeyEvent.VK_DEAD_VOICED_SOUND: return "DEAD_VOICED_SOUND";
          case KeyEvent.VK_DEAD_SEMIVOICED_SOUND: return "DEAD_SEMIVOICED_SOUND";
          case KeyEvent.VK_AMPERSAND: return "AMPERSAND";
          case KeyEvent.VK_ASTERISK: return "ASTERISK";
          case KeyEvent.VK_QUOTEDBL: return "QUOTEDBL";
          case KeyEvent.VK_LESS: return "LESS";
          case KeyEvent.VK_GREATER: return "GREATER";
          case KeyEvent.VK_BRACELEFT: return "BRACELEFT";
          case KeyEvent.VK_BRACERIGHT: return "BRACERIGHT";
          case KeyEvent.VK_AT: return "AT";
          case KeyEvent.VK_COLON: return "COLON";
          case KeyEvent.VK_CIRCUMFLEX: return "CIRCUMFLEX";
          case KeyEvent.VK_DOLLAR: return "DOLLAR";
          case KeyEvent.VK_EURO_SIGN: return "EURO_SIGN";
          case KeyEvent.VK_EXCLAMATION_MARK: return "EXCLAMATION_MARK";
          case KeyEvent.VK_INVERTED_EXCLAMATION_MARK:
                   return "INVERTED_EXCLAMATION_MARK";
          case KeyEvent.VK_LEFT_PARENTHESIS: return "LEFT_PARENTHESIS";
          case KeyEvent.VK_NUMBER_SIGN: return "NUMBER_SIGN";
          case KeyEvent.VK_MINUS: return "MINUS";
          case KeyEvent.VK_PLUS: return "PLUS";
          case KeyEvent.VK_RIGHT_PARENTHESIS: return "RIGHT_PARENTHESIS";
          case KeyEvent.VK_UNDERSCORE: return "UNDERSCORE";
          case KeyEvent.VK_FINAL: return "FINAL";
          case KeyEvent.VK_CONVERT: return "CONVERT";
          case KeyEvent.VK_NONCONVERT: return "NONCONVERT";
          case KeyEvent.VK_ACCEPT: return "ACCEPT";
          case KeyEvent.VK_MODECHANGE: return "MODECHANGE";
          case KeyEvent.VK_KANA: return "KANA";
          case KeyEvent.VK_KANJI: return "KANJI";
          case KeyEvent.VK_ALPHANUMERIC: return "ALPHANUMERIC";
          case KeyEvent.VK_KATAKANA: return "KATAKANA";
          case KeyEvent.VK_HIRAGANA: return "HIRAGANA";
          case KeyEvent.VK_FULL_WIDTH: return "FULL_WIDTH";
          case KeyEvent.VK_HALF_WIDTH: return "HALF_WIDTH";
          case KeyEvent.VK_ROMAN_CHARACTERS: return "ROMAN_CHARACTERS";
          case KeyEvent.VK_ALL_CANDIDATES: return "ALL_CANDIDATES";
          case KeyEvent.VK_PREVIOUS_CANDIDATE: return "PREVIOUS_CANDIDATE";
          case KeyEvent.VK_CODE_INPUT: return "CODE_INPUT";
          case KeyEvent.VK_JAPANESE_KATAKANA: return "JAPANESE_KATAKANA";
          case KeyEvent.VK_JAPANESE_HIRAGANA: return "JAPANESE_HIRAGANA";
          case KeyEvent.VK_JAPANESE_ROMAN: return "JAPANESE_ROMAN";
          case KeyEvent.VK_KANA_LOCK: return "KANA_LOCK";
          case KeyEvent.VK_INPUT_METHOD_ON_OFF: return "INPUT_METHOD_ON_OFF";
          case KeyEvent.VK_AGAIN: return "AGAIN";
          case KeyEvent.VK_UNDO: return "UNDO";
          case KeyEvent.VK_COPY: return "COPY";
          case KeyEvent.VK_PASTE: return "PASTE";
          case KeyEvent.VK_CUT: return "CUT";
          case KeyEvent.VK_FIND: return "FIND";
          case KeyEvent.VK_PROPS: return "PROPS";
          case KeyEvent.VK_STOP: return "STOP";
          case KeyEvent.VK_COMPOSE: return "COMPOSE";
          case KeyEvent.VK_ALT_GRAPH: return "ALT_GRAPH";
        }
        if (keyCode >= KeyEvent.VK_NUMPAD0 && keyCode <= KeyEvent.VK_NUMPAD9) {
            char c = (char)(keyCode - KeyEvent.VK_NUMPAD0 + "0");
            return "NUMPAD"+c;
        }
        return "unknown(0x" + Integer.toString(keyCode, 16) + ")";
    }
}





Listening to All Key Events Before Delivery to Focused Component

    
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class Main {
  public static void main(String[] argv) throws Exception {
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
        new KeyEventDispatcher() {
          public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_TYPED) {
              e.setKeyChar("a");
            }
            boolean discardEvent = false;
            return discardEvent;
          }
        });
  }
}





List keystrokes in the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input map of the component

    
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton();
    InputMap map = component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    list(map, map.keys());
    list(map, map.allKeys());
  }
  static void list(InputMap map, KeyStroke[] keys) {
    if (keys == null) {
      return;
    }
    for (int i = 0; i < keys.length; i++) {
      keyStroke2String(keys[i]);
      while (map.get(keys[i]) == null) {
        map = map.getParent();
      }
      if (map.get(keys[i]) instanceof String) {
        String actionName = (String) map.get(keys[i]);
      } else {
        Action action = (Action) map.get(keys[i]);
      }
    }
  }
  static void keyStroke2String(KeyStroke key) {
    int m = key.getModifiers();
    if ((m & (InputEvent.SHIFT_DOWN_MASK | InputEvent.SHIFT_MASK)) != 0) {
      System.out.println("shift ");
    }
    if ((m & (InputEvent.CTRL_DOWN_MASK | InputEvent.CTRL_MASK)) != 0) {
      System.out.println("ctrl ");
    }
    if ((m & (InputEvent.META_DOWN_MASK | InputEvent.META_MASK)) != 0) {
      System.out.println("meta ");
    }
    if ((m & (InputEvent.ALT_DOWN_MASK | InputEvent.ALT_MASK)) != 0) {
      System.out.println("alt ");
    }
    if ((m & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON1_MASK)) != 0) {
      System.out.println("button1 ");
    }
    if ((m & (InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON2_MASK)) != 0) {
      System.out.println("button2 ");
    }
    if ((m & (InputEvent.BUTTON3_DOWN_MASK | InputEvent.BUTTON3_MASK)) != 0) {
      System.out.println("button3 ");
    }
    switch (key.getKeyEventType()) {
    case KeyEvent.KEY_TYPED:
      System.out.println("typed ");
      System.out.println(key.getKeyChar() + " ");
      break;
    case KeyEvent.KEY_PRESSED:
      System.out.println("pressed ");
      System.out.println(getKeyText(key.getKeyCode()) + " ");
      break;
    case KeyEvent.KEY_RELEASED:
      System.out.println("released ");
      System.out.println(getKeyText(key.getKeyCode()) + " ");
      break;
    default:
      System.out.println("unknown-event-type ");
      break;
    }
  }
  static String getKeyText(int keyCode) {
    if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9 || keyCode >= KeyEvent.VK_A
        && keyCode <= KeyEvent.VK_Z) {
      return String.valueOf((char) keyCode);
    }
    switch (keyCode) {
    case KeyEvent.VK_COMMA:
      return "COMMA";
    case KeyEvent.VK_PERIOD:
      return "PERIOD";
    case KeyEvent.VK_SLASH:
      return "SLASH";
    case KeyEvent.VK_SEMICOLON:
      return "SEMICOLON";
    case KeyEvent.VK_EQUALS:
      return "EQUALS";
    case KeyEvent.VK_OPEN_BRACKET:
      return "OPEN_BRACKET";
    case KeyEvent.VK_BACK_SLASH:
      return "BACK_SLASH";
    case KeyEvent.VK_CLOSE_BRACKET:
      return "CLOSE_BRACKET";
    case KeyEvent.VK_ENTER:
      return "ENTER";
    case KeyEvent.VK_BACK_SPACE:
      return "BACK_SPACE";
    case KeyEvent.VK_TAB:
      return "TAB";
    case KeyEvent.VK_CANCEL:
      return "CANCEL";
    case KeyEvent.VK_CLEAR:
      return "CLEAR";
    case KeyEvent.VK_SHIFT:
      return "SHIFT";
    case KeyEvent.VK_CONTROL:
      return "CONTROL";
    case KeyEvent.VK_ALT:
      return "ALT";
    case KeyEvent.VK_PAUSE:
      return "PAUSE";
    case KeyEvent.VK_CAPS_LOCK:
      return "CAPS_LOCK";
    case KeyEvent.VK_ESCAPE:
      return "ESCAPE";
    case KeyEvent.VK_SPACE:
      return "SPACE";
    case KeyEvent.VK_PAGE_UP:
      return "PAGE_UP";
    case KeyEvent.VK_PAGE_DOWN:
      return "PAGE_DOWN";
    case KeyEvent.VK_END:
      return "END";
    case KeyEvent.VK_HOME:
      return "HOME";
    case KeyEvent.VK_LEFT:
      return "LEFT";
    case KeyEvent.VK_UP:
      return "UP";
    case KeyEvent.VK_RIGHT:
      return "RIGHT";
    case KeyEvent.VK_DOWN:
      return "DOWN";
    case KeyEvent.VK_MULTIPLY:
      return "MULTIPLY";
    case KeyEvent.VK_ADD:
      return "ADD";
    case KeyEvent.VK_SEPARATOR:
      return "SEPARATOR";
    case KeyEvent.VK_SUBTRACT:
      return "SUBTRACT";
    case KeyEvent.VK_DECIMAL:
      return "DECIMAL";
    case KeyEvent.VK_DIVIDE:
      return "DIVIDE";
    case KeyEvent.VK_DELETE:
      return "DELETE";
    case KeyEvent.VK_NUM_LOCK:
      return "NUM_LOCK";
    case KeyEvent.VK_SCROLL_LOCK:
      return "SCROLL_LOCK";
    case KeyEvent.VK_F1:
      return "F1";
    case KeyEvent.VK_F2:
      return "F2";
    case KeyEvent.VK_F3:
      return "F3";
    case KeyEvent.VK_F4:
      return "F4";
    case KeyEvent.VK_F5:
      return "F5";
    case KeyEvent.VK_F6:
      return "F6";
    case KeyEvent.VK_F7:
      return "F7";
    case KeyEvent.VK_F8:
      return "F8";
    case KeyEvent.VK_F9:
      return "F9";
    case KeyEvent.VK_F10:
      return "F10";
    case KeyEvent.VK_F11:
      return "F11";
    case KeyEvent.VK_F12:
      return "F12";
    case KeyEvent.VK_F13:
      return "F13";
    case KeyEvent.VK_F14:
      return "F14";
    case KeyEvent.VK_F15:
      return "F15";
    case KeyEvent.VK_F16:
      return "F16";
    case KeyEvent.VK_F17:
      return "F17";
    case KeyEvent.VK_F18:
      return "F18";
    case KeyEvent.VK_F19:
      return "F19";
    case KeyEvent.VK_F20:
      return "F20";
    case KeyEvent.VK_F21:
      return "F21";
    case KeyEvent.VK_F22:
      return "F22";
    case KeyEvent.VK_F23:
      return "F23";
    case KeyEvent.VK_F24:
      return "F24";
    case KeyEvent.VK_PRINTSCREEN:
      return "PRINTSCREEN";
    case KeyEvent.VK_INSERT:
      return "INSERT";
    case KeyEvent.VK_HELP:
      return "HELP";
    case KeyEvent.VK_META:
      return "META";
    case KeyEvent.VK_BACK_QUOTE:
      return "BACK_QUOTE";
    case KeyEvent.VK_QUOTE:
      return "QUOTE";
    case KeyEvent.VK_KP_UP:
      return "KP_UP";
    case KeyEvent.VK_KP_DOWN:
      return "KP_DOWN";
    case KeyEvent.VK_KP_LEFT:
      return "KP_LEFT";
    case KeyEvent.VK_KP_RIGHT:
      return "KP_RIGHT";
    case KeyEvent.VK_DEAD_GRAVE:
      return "DEAD_GRAVE";
    case KeyEvent.VK_DEAD_ACUTE:
      return "DEAD_ACUTE";
    case KeyEvent.VK_DEAD_CIRCUMFLEX:
      return "DEAD_CIRCUMFLEX";
    case KeyEvent.VK_DEAD_TILDE:
      return "DEAD_TILDE";
    case KeyEvent.VK_DEAD_MACRON:
      return "DEAD_MACRON";
    case KeyEvent.VK_DEAD_BREVE:
      return "DEAD_BREVE";
    case KeyEvent.VK_DEAD_ABOVEDOT:
      return "DEAD_ABOVEDOT";
    case KeyEvent.VK_DEAD_DIAERESIS:
      return "DEAD_DIAERESIS";
    case KeyEvent.VK_DEAD_ABOVERING:
      return "DEAD_ABOVERING";
    case KeyEvent.VK_DEAD_DOUBLEACUTE:
      return "DEAD_DOUBLEACUTE";
    case KeyEvent.VK_DEAD_CARON:
      return "DEAD_CARON";
    case KeyEvent.VK_DEAD_CEDILLA:
      return "DEAD_CEDILLA";
    case KeyEvent.VK_DEAD_OGONEK:
      return "DEAD_OGONEK";
    case KeyEvent.VK_DEAD_IOTA:
      return "DEAD_IOTA";
    case KeyEvent.VK_DEAD_VOICED_SOUND:
      return "DEAD_VOICED_SOUND";
    case KeyEvent.VK_DEAD_SEMIVOICED_SOUND:
      return "DEAD_SEMIVOICED_SOUND";
    case KeyEvent.VK_AMPERSAND:
      return "AMPERSAND";
    case KeyEvent.VK_ASTERISK:
      return "ASTERISK";
    case KeyEvent.VK_QUOTEDBL:
      return "QUOTEDBL";
    case KeyEvent.VK_LESS:
      return "LESS";
    case KeyEvent.VK_GREATER:
      return "GREATER";
    case KeyEvent.VK_BRACELEFT:
      return "BRACELEFT";
    case KeyEvent.VK_BRACERIGHT:
      return "BRACERIGHT";
    case KeyEvent.VK_AT:
      return "AT";
    case KeyEvent.VK_COLON:
      return "COLON";
    case KeyEvent.VK_CIRCUMFLEX:
      return "CIRCUMFLEX";
    case KeyEvent.VK_DOLLAR:
      return "DOLLAR";
    case KeyEvent.VK_EURO_SIGN:
      return "EURO_SIGN";
    case KeyEvent.VK_EXCLAMATION_MARK:
      return "EXCLAMATION_MARK";
    case KeyEvent.VK_INVERTED_EXCLAMATION_MARK:
      return "INVERTED_EXCLAMATION_MARK";
    case KeyEvent.VK_LEFT_PARENTHESIS:
      return "LEFT_PARENTHESIS";
    case KeyEvent.VK_NUMBER_SIGN:
      return "NUMBER_SIGN";
    case KeyEvent.VK_MINUS:
      return "MINUS";
    case KeyEvent.VK_PLUS:
      return "PLUS";
    case KeyEvent.VK_RIGHT_PARENTHESIS:
      return "RIGHT_PARENTHESIS";
    case KeyEvent.VK_UNDERSCORE:
      return "UNDERSCORE";
    case KeyEvent.VK_FINAL:
      return "FINAL";
    case KeyEvent.VK_CONVERT:
      return "CONVERT";
    case KeyEvent.VK_NONCONVERT:
      return "NONCONVERT";
    case KeyEvent.VK_ACCEPT:
      return "ACCEPT";
    case KeyEvent.VK_MODECHANGE:
      return "MODECHANGE";
    case KeyEvent.VK_KANA:
      return "KANA";
    case KeyEvent.VK_KANJI:
      return "KANJI";
    case KeyEvent.VK_ALPHANUMERIC:
      return "ALPHANUMERIC";
    case KeyEvent.VK_KATAKANA:
      return "KATAKANA";
    case KeyEvent.VK_HIRAGANA:
      return "HIRAGANA";
    case KeyEvent.VK_FULL_WIDTH:
      return "FULL_WIDTH";
    case KeyEvent.VK_HALF_WIDTH:
      return "HALF_WIDTH";
    case KeyEvent.VK_ROMAN_CHARACTERS:
      return "ROMAN_CHARACTERS";
    case KeyEvent.VK_ALL_CANDIDATES:
      return "ALL_CANDIDATES";
    case KeyEvent.VK_PREVIOUS_CANDIDATE:
      return "PREVIOUS_CANDIDATE";
    case KeyEvent.VK_CODE_INPUT:
      return "CODE_INPUT";
    case KeyEvent.VK_JAPANESE_KATAKANA:
      return "JAPANESE_KATAKANA";
    case KeyEvent.VK_JAPANESE_HIRAGANA:
      return "JAPANESE_HIRAGANA";
    case KeyEvent.VK_JAPANESE_ROMAN:
      return "JAPANESE_ROMAN";
    case KeyEvent.VK_KANA_LOCK:
      return "KANA_LOCK";
    case KeyEvent.VK_INPUT_METHOD_ON_OFF:
      return "INPUT_METHOD_ON_OFF";
    case KeyEvent.VK_AGAIN:
      return "AGAIN";
    case KeyEvent.VK_UNDO:
      return "UNDO";
    case KeyEvent.VK_COPY:
      return "COPY";
    case KeyEvent.VK_PASTE:
      return "PASTE";
    case KeyEvent.VK_CUT:
      return "CUT";
    case KeyEvent.VK_FIND:
      return "FIND";
    case KeyEvent.VK_PROPS:
      return "PROPS";
    case KeyEvent.VK_STOP:
      return "STOP";
    case KeyEvent.VK_COMPOSE:
      return "COMPOSE";
    case KeyEvent.VK_ALT_GRAPH:
      return "ALT_GRAPH";
    }
    if (keyCode >= KeyEvent.VK_NUMPAD0 && keyCode <= KeyEvent.VK_NUMPAD9) {
      char c = (char) (keyCode - KeyEvent.VK_NUMPAD0 + "0");
      return "NUMPAD" + c;
    }
    return "unknown(0x" + Integer.toString(keyCode, 16) + ")";
  }
}





List keystrokes in the WHEN_IN_FOCUSED_WINDOW input map of the component

    
    
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton("button");
    InputMap map = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    list(map, map.keys());
    list(map, map.allKeys());
  }
  static void list(InputMap map, KeyStroke[] keys) {
    if (keys == null) {
      return;
    }
    for (int i = 0; i < keys.length; i++) {
      keyStroke2String(keys[i]);
      while (map.get(keys[i]) == null) {
        map = map.getParent();
      }
      if (map.get(keys[i]) instanceof String) {
        String actionName = (String) map.get(keys[i]);
      } else {
        Action action = (Action) map.get(keys[i]);
      }
    }
  }
  static void keyStroke2String(KeyStroke key) {
    int m = key.getModifiers();
    if ((m & (InputEvent.SHIFT_DOWN_MASK | InputEvent.SHIFT_MASK)) != 0) {
      System.out.println("shift ");
    }
    if ((m & (InputEvent.CTRL_DOWN_MASK | InputEvent.CTRL_MASK)) != 0) {
      System.out.println("ctrl ");
    }
    if ((m & (InputEvent.META_DOWN_MASK | InputEvent.META_MASK)) != 0) {
      System.out.println("meta ");
    }
    if ((m & (InputEvent.ALT_DOWN_MASK | InputEvent.ALT_MASK)) != 0) {
      System.out.println("alt ");
    }
    if ((m & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON1_MASK)) != 0) {
      System.out.println("button1 ");
    }
    if ((m & (InputEvent.BUTTON2_DOWN_MASK | InputEvent.BUTTON2_MASK)) != 0) {
      System.out.println("button2 ");
    }
    if ((m & (InputEvent.BUTTON3_DOWN_MASK | InputEvent.BUTTON3_MASK)) != 0) {
      System.out.println("button3 ");
    }
    switch (key.getKeyEventType()) {
    case KeyEvent.KEY_TYPED:
      System.out.println("typed ");
      System.out.println(key.getKeyChar() + " ");
      break;
    case KeyEvent.KEY_PRESSED:
      System.out.println("pressed ");
      System.out.println(getKeyText(key.getKeyCode()) + " ");
      break;
    case KeyEvent.KEY_RELEASED:
      System.out.println("released ");
      System.out.println(getKeyText(key.getKeyCode()) + " ");
      break;
    default:
      System.out.println("unknown-event-type ");
      break;
    }
  }
  static String getKeyText(int keyCode) {
    if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9 || keyCode >= KeyEvent.VK_A
        && keyCode <= KeyEvent.VK_Z) {
      return String.valueOf((char) keyCode);
    }
    switch (keyCode) {
    case KeyEvent.VK_COMMA:
      return "COMMA";
    case KeyEvent.VK_PERIOD:
      return "PERIOD";
    case KeyEvent.VK_SLASH:
      return "SLASH";
    case KeyEvent.VK_SEMICOLON:
      return "SEMICOLON";
    case KeyEvent.VK_EQUALS:
      return "EQUALS";
    case KeyEvent.VK_OPEN_BRACKET:
      return "OPEN_BRACKET";
    case KeyEvent.VK_BACK_SLASH:
      return "BACK_SLASH";
    case KeyEvent.VK_CLOSE_BRACKET:
      return "CLOSE_BRACKET";
    case KeyEvent.VK_ENTER:
      return "ENTER";
    case KeyEvent.VK_BACK_SPACE:
      return "BACK_SPACE";
    case KeyEvent.VK_TAB:
      return "TAB";
    case KeyEvent.VK_CANCEL:
      return "CANCEL";
    case KeyEvent.VK_CLEAR:
      return "CLEAR";
    case KeyEvent.VK_SHIFT:
      return "SHIFT";
    case KeyEvent.VK_CONTROL:
      return "CONTROL";
    case KeyEvent.VK_ALT:
      return "ALT";
    case KeyEvent.VK_PAUSE:
      return "PAUSE";
    case KeyEvent.VK_CAPS_LOCK:
      return "CAPS_LOCK";
    case KeyEvent.VK_ESCAPE:
      return "ESCAPE";
    case KeyEvent.VK_SPACE:
      return "SPACE";
    case KeyEvent.VK_PAGE_UP:
      return "PAGE_UP";
    case KeyEvent.VK_PAGE_DOWN:
      return "PAGE_DOWN";
    case KeyEvent.VK_END:
      return "END";
    case KeyEvent.VK_HOME:
      return "HOME";
    case KeyEvent.VK_LEFT:
      return "LEFT";
    case KeyEvent.VK_UP:
      return "UP";
    case KeyEvent.VK_RIGHT:
      return "RIGHT";
    case KeyEvent.VK_DOWN:
      return "DOWN";
    case KeyEvent.VK_MULTIPLY:
      return "MULTIPLY";
    case KeyEvent.VK_ADD:
      return "ADD";
    case KeyEvent.VK_SEPARATOR:
      return "SEPARATOR";
    case KeyEvent.VK_SUBTRACT:
      return "SUBTRACT";
    case KeyEvent.VK_DECIMAL:
      return "DECIMAL";
    case KeyEvent.VK_DIVIDE:
      return "DIVIDE";
    case KeyEvent.VK_DELETE:
      return "DELETE";
    case KeyEvent.VK_NUM_LOCK:
      return "NUM_LOCK";
    case KeyEvent.VK_SCROLL_LOCK:
      return "SCROLL_LOCK";
    case KeyEvent.VK_F1:
      return "F1";
    case KeyEvent.VK_F2:
      return "F2";
    case KeyEvent.VK_F3:
      return "F3";
    case KeyEvent.VK_F4:
      return "F4";
    case KeyEvent.VK_F5:
      return "F5";
    case KeyEvent.VK_F6:
      return "F6";
    case KeyEvent.VK_F7:
      return "F7";
    case KeyEvent.VK_F8:
      return "F8";
    case KeyEvent.VK_F9:
      return "F9";
    case KeyEvent.VK_F10:
      return "F10";
    case KeyEvent.VK_F11:
      return "F11";
    case KeyEvent.VK_F12:
      return "F12";
    case KeyEvent.VK_F13:
      return "F13";
    case KeyEvent.VK_F14:
      return "F14";
    case KeyEvent.VK_F15:
      return "F15";
    case KeyEvent.VK_F16:
      return "F16";
    case KeyEvent.VK_F17:
      return "F17";
    case KeyEvent.VK_F18:
      return "F18";
    case KeyEvent.VK_F19:
      return "F19";
    case KeyEvent.VK_F20:
      return "F20";
    case KeyEvent.VK_F21:
      return "F21";
    case KeyEvent.VK_F22:
      return "F22";
    case KeyEvent.VK_F23:
      return "F23";
    case KeyEvent.VK_F24:
      return "F24";
    case KeyEvent.VK_PRINTSCREEN:
      return "PRINTSCREEN";
    case KeyEvent.VK_INSERT:
      return "INSERT";
    case KeyEvent.VK_HELP:
      return "HELP";
    case KeyEvent.VK_META:
      return "META";
    case KeyEvent.VK_BACK_QUOTE:
      return "BACK_QUOTE";
    case KeyEvent.VK_QUOTE:
      return "QUOTE";
    case KeyEvent.VK_KP_UP:
      return "KP_UP";
    case KeyEvent.VK_KP_DOWN:
      return "KP_DOWN";
    case KeyEvent.VK_KP_LEFT:
      return "KP_LEFT";
    case KeyEvent.VK_KP_RIGHT:
      return "KP_RIGHT";
    case KeyEvent.VK_DEAD_GRAVE:
      return "DEAD_GRAVE";
    case KeyEvent.VK_DEAD_ACUTE:
      return "DEAD_ACUTE";
    case KeyEvent.VK_DEAD_CIRCUMFLEX:
      return "DEAD_CIRCUMFLEX";
    case KeyEvent.VK_DEAD_TILDE:
      return "DEAD_TILDE";
    case KeyEvent.VK_DEAD_MACRON:
      return "DEAD_MACRON";
    case KeyEvent.VK_DEAD_BREVE:
      return "DEAD_BREVE";
    case KeyEvent.VK_DEAD_ABOVEDOT:
      return "DEAD_ABOVEDOT";
    case KeyEvent.VK_DEAD_DIAERESIS:
      return "DEAD_DIAERESIS";
    case KeyEvent.VK_DEAD_ABOVERING:
      return "DEAD_ABOVERING";
    case KeyEvent.VK_DEAD_DOUBLEACUTE:
      return "DEAD_DOUBLEACUTE";
    case KeyEvent.VK_DEAD_CARON:
      return "DEAD_CARON";
    case KeyEvent.VK_DEAD_CEDILLA:
      return "DEAD_CEDILLA";
    case KeyEvent.VK_DEAD_OGONEK:
      return "DEAD_OGONEK";
    case KeyEvent.VK_DEAD_IOTA:
      return "DEAD_IOTA";
    case KeyEvent.VK_DEAD_VOICED_SOUND:
      return "DEAD_VOICED_SOUND";
    case KeyEvent.VK_DEAD_SEMIVOICED_SOUND:
      return "DEAD_SEMIVOICED_SOUND";
    case KeyEvent.VK_AMPERSAND:
      return "AMPERSAND";
    case KeyEvent.VK_ASTERISK:
      return "ASTERISK";
    case KeyEvent.VK_QUOTEDBL:
      return "QUOTEDBL";
    case KeyEvent.VK_LESS:
      return "LESS";
    case KeyEvent.VK_GREATER:
      return "GREATER";
    case KeyEvent.VK_BRACELEFT:
      return "BRACELEFT";
    case KeyEvent.VK_BRACERIGHT:
      return "BRACERIGHT";
    case KeyEvent.VK_AT:
      return "AT";
    case KeyEvent.VK_COLON:
      return "COLON";
    case KeyEvent.VK_CIRCUMFLEX:
      return "CIRCUMFLEX";
    case KeyEvent.VK_DOLLAR:
      return "DOLLAR";
    case KeyEvent.VK_EURO_SIGN:
      return "EURO_SIGN";
    case KeyEvent.VK_EXCLAMATION_MARK:
      return "EXCLAMATION_MARK";
    case KeyEvent.VK_INVERTED_EXCLAMATION_MARK:
      return "INVERTED_EXCLAMATION_MARK";
    case KeyEvent.VK_LEFT_PARENTHESIS:
      return "LEFT_PARENTHESIS";
    case KeyEvent.VK_NUMBER_SIGN:
      return "NUMBER_SIGN";
    case KeyEvent.VK_MINUS:
      return "MINUS";
    case KeyEvent.VK_PLUS:
      return "PLUS";
    case KeyEvent.VK_RIGHT_PARENTHESIS:
      return "RIGHT_PARENTHESIS";
    case KeyEvent.VK_UNDERSCORE:
      return "UNDERSCORE";
    case KeyEvent.VK_FINAL:
      return "FINAL";
    case KeyEvent.VK_CONVERT:
      return "CONVERT";
    case KeyEvent.VK_NONCONVERT:
      return "NONCONVERT";
    case KeyEvent.VK_ACCEPT:
      return "ACCEPT";
    case KeyEvent.VK_MODECHANGE:
      return "MODECHANGE";
    case KeyEvent.VK_KANA:
      return "KANA";
    case KeyEvent.VK_KANJI:
      return "KANJI";
    case KeyEvent.VK_ALPHANUMERIC:
      return "ALPHANUMERIC";
    case KeyEvent.VK_KATAKANA:
      return "KATAKANA";
    case KeyEvent.VK_HIRAGANA:
      return "HIRAGANA";
    case KeyEvent.VK_FULL_WIDTH:
      return "FULL_WIDTH";
    case KeyEvent.VK_HALF_WIDTH:
      return "HALF_WIDTH";
    case KeyEvent.VK_ROMAN_CHARACTERS:
      return "ROMAN_CHARACTERS";
    case KeyEvent.VK_ALL_CANDIDATES:
      return "ALL_CANDIDATES";
    case KeyEvent.VK_PREVIOUS_CANDIDATE:
      return "PREVIOUS_CANDIDATE";
    case KeyEvent.VK_CODE_INPUT:
      return "CODE_INPUT";
    case KeyEvent.VK_JAPANESE_KATAKANA:
      return "JAPANESE_KATAKANA";
    case KeyEvent.VK_JAPANESE_HIRAGANA:
      return "JAPANESE_HIRAGANA";
    case KeyEvent.VK_JAPANESE_ROMAN:
      return "JAPANESE_ROMAN";
    case KeyEvent.VK_KANA_LOCK:
      return "KANA_LOCK";
    case KeyEvent.VK_INPUT_METHOD_ON_OFF:
      return "INPUT_METHOD_ON_OFF";
    case KeyEvent.VK_AGAIN:
      return "AGAIN";
    case KeyEvent.VK_UNDO:
      return "UNDO";
    case KeyEvent.VK_COPY:
      return "COPY";
    case KeyEvent.VK_PASTE:
      return "PASTE";
    case KeyEvent.VK_CUT:
      return "CUT";
    case KeyEvent.VK_FIND:
      return "FIND";
    case KeyEvent.VK_PROPS:
      return "PROPS";
    case KeyEvent.VK_STOP:
      return "STOP";
    case KeyEvent.VK_COMPOSE:
      return "COMPOSE";
    case KeyEvent.VK_ALT_GRAPH:
      return "ALT_GRAPH";
    }
    if (keyCode >= KeyEvent.VK_NUMPAD0 && keyCode <= KeyEvent.VK_NUMPAD9) {
      char c = (char) (keyCode - KeyEvent.VK_NUMPAD0 + "0");
      return "NUMPAD" + c;
    }
    return "unknown(0x" + Integer.toString(keyCode, 16) + ")";
  }
}





Map actions with keystrokes

    
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Hashtable;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
import javax.swing.text.TextAction;
import javax.swing.text.Utilities;
public class Main {
  public static void main(String[] args) {
    JTextArea area = new JTextArea(6, 32);
    Keymap parent = area.getKeymap();
    Keymap newmap = JTextComponent.addKeymap("KeymapExampleMap", parent);
    KeyStroke u = KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK);
    Action actionU = new UppercaseAction();
    newmap.addActionForKeyStroke(u, actionU);
    Action actionList[] = area.getActions();
    Hashtable lookup = new Hashtable();
    for (int j = 0; j < actionList.length; j += 1)
      lookup.put(actionList[j].getValue(Action.NAME), actionList[j]);
    KeyStroke L = KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK);
    Action actionL = (Action) lookup.get(DefaultEditorKit.selectLineAction);
    newmap.addActionForKeyStroke(L, actionL);
    area.setKeymap(newmap);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new JScrollPane(area), BorderLayout.CENTER);
    area.setText("this is a test");
    f.setSize(300,300);
    f.setVisible(true);
  }
}
class UppercaseAction extends TextAction {
  public UppercaseAction() {
    super("uppercase-word-action");
  }
  public void actionPerformed(ActionEvent e) {
    JTextComponent comp = getTextComponent(e);
    if (comp == null)
      return;
    Document doc = comp.getDocument();
    int start = comp.getSelectionStart();
    int end = comp.getSelectionEnd();
    try {
      int left = Utilities.getWordStart(comp, start);
      int right = Utilities.getWordEnd(comp, end);
      String word = doc.getText(left, right - left);
      doc.remove(left, right - left);
      doc.insertString(left, word.toUpperCase(), null);
      comp.setSelectionStart(start); 
      comp.setSelectionEnd(end);
    } catch (Exception ble) {
      return;
    }
  }
}





Reads for modifiers and creates integer with required mask

  
import java.awt.event.KeyEvent;
import java.util.NoSuchElementException;
/*
 * $Id: Utilities.java,v 1.11 2008/10/14 22:31:46 rah003 Exp $
 *
 * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

/**
 * Contribution from NetBeans: Issue #319-swingx.
 * <p>
 * 
 * PENDING: need to reconcile with OS, JVM... added as-is because needed the
 * shortcut handling to fix #
 * 
 * @author apple
 */
public class Utils {
  private static final int CTRL_WILDCARD_MASK = 32768;
  private static final int ALT_WILDCARD_MASK = CTRL_WILDCARD_MASK * 2;
  /** 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;
          case "D":
              m |= CTRL_WILDCARD_MASK;
              break;
          case "O":
              m |= ALT_WILDCARD_MASK;
              break;
          default:
              throw new NoSuchElementException(s);
          }
      }
      return m;
  }
  
}





Set<AWTKeyStroke> java.awt.Container.getFocusTraversalKeys(int id)

    
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton("a");
    Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(component
        .getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
    set.add(KeyStroke.getKeyStroke("F2"));
    component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
  }
}





void InputMap.put(KeyStroke keyStroke, Object actionMapKey)

    

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton();
    MyAction action = new MyAction();
    component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
        action.getValue(Action.NAME));
  }
}
class MyAction extends AbstractAction {
  public MyAction() {
    super("my action");
  }
  public void actionPerformed(ActionEvent e) {
    System.out.println("hi");
  }
}