How to intercept KeyPressEvent in Java GWT?
I am new to Java and in our code we are using GWT.
We are using KeyPressEvent
to process the Key_Enter
request. But it seems, for each enter request, two events fired from KeyPressEvent
. But I expect only one event should be fired, since I enter only one time.
The following is my co开发者_如何学Cde. Please check and let me know, anything that we need to correct ..
void onEnter(KeyPressEvent event)
{
if(event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
{
//(seems to times this code is called)
//Domy stuff
}
}
If I use event.getCharCode()
instead of event.getNativeEvent().getKeyCode()
, it only returns 0.
Any idea how to fix.
Thanks,
I prefer using KeyUpEvent
because the user can't distinguish it from KeyPressEvent
so here is my solution:
void onKeyUp(KeyUpEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
// Handle key press
}
}
The JavaDoc of KeyEvent warns that browser idiosyncrasies in keyboard handling are not completely normalized by GWT. Following is a quote from the docs:
The native keyboard events are somewhat a mess (http://www.quirksmode.org/js/keys.html), we do some trivial normalization here, but do not attempt any complex patching, so user be warned.
What this means is that browser are not consistent in how they fire different keyboard events and you should handle the quirks in your own code.
Read http://www.quirksmode.org/js/keys.html to find out more.
Try calling sinkEvents on the widget which tries to listen. This should be done immediately after the widget is constructed.
widget.sinkEvents(Event.KEYEVENTS)
KeyPressEvent
is for key presses that result in an actual character code - like pressing the 'a' key. If you want to be notified when the enter key is pressed use KeyDownEvent
instead:
void onEnter(KeyDownEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
// Handle key press
}
}
精彩评论