如何更改生成的KeyEvent的字段?
键盘上的实际KeyEvent
java.awt.event.KeyEvent[KEY_PRESSED,
keyCode=65,
keyText=A,
keyChar='a',
keyLocation=KEY_LOCATION_STANDARD,
rawCode=65,
primaryLevelUnicode=97,
scancode=30,
extendedKeyCode=0x41] on panel0
Generated KeyEvent
java.awt.event.KeyEvent[KEY_PRESSED,
keyCode=65,
keyText=A,
keyChar='a',
keyLocation=KEY_LOCATION_STANDARD,
rawCode=0,
primaryLevelUnicode=0,
scancode=0,
extendedKeyCode=0x0] on panel0
new KeyEvent(component, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, 65, 'a')
差分
rawCode
primaryLevelUnicode
scancode
extendedKeyCode
有没有办法在KeyEvent对象上设置这些字段?
文档https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
答案 0 :(得分:0)
查看KeyEvent
课程中的来源,看来你无法设置:
//set from native code.
private transient long rawCode = 0;
private transient long primaryLevelUnicode = 0;
private transient long scancode = 0; // for MS Windows only
private transient long extendedKeyCode = 0;
它是私有的,并且是从本机代码设置的(所以Java中没有变化)。
答案 1 :(得分:0)
您可以使用反射:
KeyEvent m = new KeyEvent(component, type, System.currentTimeMillis(), 0, ext,(char)key, KEY_LOCATION_STANDARD);
try
{
Field f = m.getClass().getDeclaredField("rawCode");
f.setAccessible(true);
f.setLong(m, key);
f = m.getClass().getDeclaredField("primaryLevelUnicode");
f.setAccessible(true);
f.setLong(m, key);
f = m.getClass().getDeclaredField("scancode");
f.setAccessible(true);
f.setLong(m, scanCode);
}
catch (Exception e)
{
e.printStackTrace();
}