Java tutorial
//package com.java2s; /******************************************************************************* * Copyright (c) 2010 BSI Business Systems Integration AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ import java.awt.event.KeyEvent; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Main { /** * Key to lowercase String, extracts the effective key that was pressed * (without shift, control, alt) */ public static String getKeyText(KeyEvent e) { // special cases if (e.getKeyCode() == KeyEvent.VK_DELETE) { return "delete"; } // prio 1: get text of unresolved code (shift-1 --> '1') String s = "" + e.getKeyChar(); if (e.getKeyCode() > 0) { int flags = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL; for (Field f : KeyEvent.class.getFields()) { if ((f.getModifiers() & flags) == flags) { try { if (f.getName().startsWith("VK_") && ((Integer) f.get(null)) == e.getKeyCode()) { s = f.getName().substring(3).toLowerCase(); break; } } catch (Throwable t) { // nop } } } } if (s.length() != 1) { // prio 2: check if the resolved char is valid (shift-1 --> '+') if (e.getKeyChar() >= 32 && e.getKeyChar() < 128) { s = "" + e.getKeyChar(); } } return s.toLowerCase(); } }