Skip to content

Instantly share code, notes, and snippets.

@xkr47
Last active January 28, 2016 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xkr47/3d35584496859a599b72 to your computer and use it in GitHub Desktop.
Save xkr47/3d35584496859a599b72 to your computer and use it in GitHub Desktop.
How to get the private rawCode field out of a Java Swing KeyEvent
import java.awt.event {
KeyEvent
}
import java.lang {
Runnable,
JBoolean=Boolean,
JLong=Long
}
import java.lang.reflect {
Field
}
Field getRawCodeField() {
value c = javaClass<KeyEvent>();
value f = c.getDeclaredField("rawCode");
javaClass<Field>().getMethod("setAccessible", JBoolean.\iTYPE).invoke(f, JBoolean(true));
return f;
}
Field rawCodeField = getRawCodeField();
shared Integer getRawCode(KeyEvent e) {
assert(is JLong v = rawCodeField.get(e));
return v.longValue();
}
// ...
shared actual void keyPressed(KeyEvent? keyEvent) {
if (!exists keyEvent) { return; }
value rawCode = getRawCode(keyEvent);
print(rawCode);
}
@xkr47
Copy link
Author

xkr47 commented Jan 28, 2016

And if you want to get events for the TAB key as well, remember to do

component.focusTraversalKeysEnabled = false;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment