Java examples for Swing:Key Event
Returns a unique text for a KeyEvent code
/* $Id$// www. j ava2 s .c o m ***************************************************************************** * Copyright (c) 2009 Contributors - see below * 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: * mvw ***************************************************************************** * * Some portions of this file was previously release using the BSD License: */ //package com.java2s; import java.awt.event.KeyEvent; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Main { /** * Returns a unique text for a KeyEvent code * * @param keyCode the keyCode to be "translated" * @return the corrisponding text for the keyCode */ public static String getKeyText(int keyCode) { int expectedModifiers = (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL); Field[] fields = KeyEvent.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { if (fields[i].getModifiers() == expectedModifiers && fields[i].getType() == Integer.TYPE && fields[i].getName().startsWith("VK_") && fields[i].getInt(KeyEvent.class) == keyCode) { return fields[i].getName().substring(3); } } catch (IllegalAccessException e) { } } return "UNKNOWN"; } }