KeyCodes.KEY_ESCAPE

74 views
Skip to first unread message

Antoine Lever

unread,
Sep 10, 2012, 11:50:52 AM9/10/12
to google-we...@googlegroups.com
Could anyone tell me why this code fragment traps the Enter key perfectly well but doesn't trap the Escape key?

textBox.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
int code = event.getNativeEvent().getCharCode();
if (code == KeyCodes.KEY_ENTER) {
fp.setText(row, col, tb.getText());
}
if (code == (char) KeyCodes.KEY_ESCAPE) { 
fp.setText(row, col, old);
System.out.println("GOT TO ESCAPE");
}
}
});

Please help!
Thank you. 

Abraham Lin

unread,
Sep 10, 2012, 12:18:10 PM9/10/12
to google-we...@googlegroups.com
The keypress event tends to be handled inconsistently by different browsers/environments:  http://www.quirksmode.org/js/keys.html

As noted in the link above, you should probably stick with keyup or keydown events.

-Abraham

Thomas Broyer

unread,
Sep 10, 2012, 12:38:49 PM9/10/12
to google-we...@googlegroups.com
There's a good reason KeyPressEvent reasons in terms of "char codes" (and more precisely, "printable characters", even though Firefox keeps firing way too much KeyPressEvents, but with a 0 "char code") and KeyDown/KeyUpEvent in terms of "key codes".
Also, Firefox keeps treating the the enter key as no producing characters, such that you'll have a KeyPressEvent with a 0 char code. See http://code.google.com/p/google-web-toolkit/issues/detail?id=5003

Antoine Lever

unread,
Sep 10, 2012, 1:03:13 PM9/10/12
to google-we...@googlegroups.com
Thanks for your help, it's much appreciated.  Below is the code that works for everyone who will spend hours Googling this:

textbox.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
int code = (int) event.getNativeEvent().getKeyCode();
if (code == KeyCodes.KEY_ENTER) {
fp.setText(row, col, tb.getText());
}
if (code == KeyCodes.KEY_ESCAPE) { 
fp.setText(row, col, old);
System.out.println("GOT TO ESCAPE");
}
}
});
Reply all
Reply to author
Forward
0 new messages