Java tutorial
//package com.java2s; import java.awt.event.KeyEvent; import java.lang.reflect.Field; import javax.swing.AbstractButton; public class Main { /** * Uses the value returned via the component's getText() method to set a Mnemonic key. * The character following the first '&' charcater is used as Mnemonic key, * but this only works for characters in the range a..Z * If a Mnemonic key is found, the '&' character is removed from the text. * @param textComponent */ public static void setMnemonic(AbstractButton textComponent) { String label = textComponent.getText(); if (label == null || label.isEmpty() || !label.contains("&") || label.indexOf('&') == label.length() - 1) { return; } char ch = label.charAt(label.indexOf('&') + 1); if (!Character.isLetter(ch)) { return; } int ke = getKeyEvent(ch); if (ke != Integer.MIN_VALUE) { label = label.substring(0, label.indexOf('&')) + label.substring(label.indexOf('&') + 1, label.length()); textComponent.setText(label); textComponent.setMnemonic(ke); } } /** * Returns the KeyEvent-code (only for VK_a..Z). * If no key-event could be found, {@link Integer#MIN_VALUE} is returned. */ public static int getKeyEvent(Character ch) { int ke = Integer.MIN_VALUE; try { Field f = KeyEvent.class.getField("VK_" + Character.toUpperCase(ch)); f.setAccessible(true); ke = (Integer) f.get(null); } catch (Exception e) { } return ke; } }