私はあなたがやろうとしていることを見ます。他の答えはどれも正しくありません。
与えられた文字の「正しい」KeyEvent
定数を取得したいのですが、膨大な行数になるルックアップ テーブルを作成する必要はありません。
確かに、反射はここであなたを助けます。かなり遅くなります。しかし、それは仕事をします。仕事が実際に行う必要があるかどうかは別の問題です。:-)
問題の関数は、おそらく次のようなものです。
/**
* 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);
}
次に、次のようにフィードできますが、提供さString
れたに文字が含まれていると、さまざまな問題が発生します。上記の関数は、例外を適切に処理するように編集されていません。
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;
}
このコードはすべてテストされていません。幸運を。まだ複雑すぎる問題が発生していると思いますが、うまくいけば、これで正しい方向に進むことができます。