问题
My code:
@Override
public void onKeyPress(KeyPressEvent event)
{
if (event.getCharCode() == KeyCodes.KEY_ENTER)
{
registerButton.click();
}
}
This is attached to a TextBox, and it does fire when I press enter. event.getCharCode()
is just zero, not 13
. When I press tab, it's 0
, and when I press escape, it's 0
. Argh!
This was working properly yesterday, and something has changed somewhere else in the project to affect this - but I'm not sure what it could be. It really seems like no relevant changes have been made in the last day.
If instead I handle a KeyUpEvent
, this works as expected.
I'm using GWT 2.1.0. Thanks for any ideas!
回答1:
the KeyPressHandler
is used for example for the SHIFT, CTRL, ALT keys.
If you want to attach an event to another key you have to use KeyDownHandler
.
nameField.addKeyDownHandler(new KeyDownHandler() {
@Override
public void onKeyDown(KeyDownEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
Window.alert("hello");
}
}
});
回答2:
or you can try this
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
}
回答3:
KeyUpHandler should be used instead of KeyPresshandler.
newSymbolTextBox.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
addStock();
}
}
});
回答4:
They might change the behavior on FF. I'm using GWT 2.4.0, and Firefox 10. According to this comment, You should use something like below before they fix the problem:
@Override
public void onKeyPress(KeyPressEvent event) {
int keyCode = event.getUnicodeCharCode();
if (keyCode == 0) {
// Probably Firefox
keyCode = event.getNativeEvent().getKeyCode();
}
if (keyCode == KeyCodes.KEY_ENTER) {
// Do something when Enter is pressed.
}
}
回答5:
I got the same problem when updating from 2.0.4 to 2.2.1, so it seems to be related to the gwt code.
Part of the issue is that KeyPressedEvent represents a native (ie browser-specific) key press event. In the bug you filed on this issue, one of the comments says:
It is however expected that "escape" does not generate a KeyPressEvent (IE and WebKit behavior); you have to use KeyDown or KeyUp for those. Firefox (and Opera) unfortunately fires many more keypress events than others (IE and WebKit, which have the most sensible implementation, the one the W3C is about to standardize in DOM 3 Events, AFAICT), but in that case getCharCode() is 0 so you can safely ignore them. The one exception (there might be others) is the "enter" key. Key/char events in browsers are such a mess that GWT doesn't do much to homogenize things (at least for now).
Until this mess is sorted out, your best bet is to use the workaround with KeyDownHandler or KeyUpHandler.
回答6:
GWT 2.5:
public void onKeyPress(KeyPressEvent event) {
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
// Event
}
}
来源:https://stackoverflow.com/questions/4115770/keypressevent-getcharcode-returning-0-for-all-special-keys-like-enter-tab-es