I see what you are trying to do. None of the other answers is correct.
You want to obtain the "correct" KeyEvent
constant for a given character, and you want to do so without having to write some kind of lookup table that would be a zillion lines long.
Indeed, reflection will help you out here. It will be reasonably slow. But it will do the job. Whether the job actually needs doing is another question. :-)
The function in question you want is probably something like this:
/**
* If possible, returns an {@code int} equal to one of the {@code public
* static final int} constants present in the {@link KeyEvent} class
* whose names start with {@code VK_}.
*
* <p>This implementation does no error handling whatsoever and has not
* been tested or compiled.</p>
*
* <p>This method is placed explicitly in the public domain.</p>
*
* @param c the character to use while searching for a field; no attempt
* will be made by this implementation to validate it in any way
*
* @return a {@link KeyEvent} constant whose name starts with {@code VK_}
*
* @exception Exception for any of a number of possible reasons
*/
public int getKeyEventConstant(final char c) throws Exception {
final Field field = KeyEvent.class.getField(String.format("VK_%S", Character.valueOf(c)));
assert field != null;
return field.getInt(null);
}
Then, you could feed it like the following, although you will have all sorts of problems if the supplied String
contains characters the function I described above is not edited to deal with exceptions properly:
public toKeyEventCodes(final String s) {
int[] returnValue = null;
if (s != null && !s.isEmpty()) {
final Collection<Integer> codes = new ArrayList<Integer>(s.length());
final char[] chars = s.toCharArray();
assert chars != null;
assert chars.length > 0;
for (final char c : chars) {
if (!Character.isWhitespace(c)) { // TODO: weed out other obvious dumb chars
codes.add(Integer.valueOf(getKeyEventConstant(c)));
}
}
returnValue = codes.toArray(new int[codes.size()]);
}
if (returnValue == null) {
returnValue = new int[0];
}
return returnValue;
}
All of this code is untested. Good luck. I'm guessing that you still have something overly complicated going on but hopefully this will get you pointed in the right direction.