keyPressEvent.getCharCode() returning 0 for all special keys like enter, tab, escape, etc

萝らか妹 提交于 2019-11-28 18:37:42
Michaël

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");
        }

    }

});
Daniel Cerecedo

or you can try this

if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
}
user2015482

KeyUpHandler should be used instead of KeyPresshandler.

newSymbolTextBox.addKeyUpHandler(new KeyUpHandler() {
    @Override
    public void onKeyUp(KeyUpEvent event) {
        if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
            addStock();
        }
    }
});

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.
    }
}

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.

GWT 2.5:

public void onKeyPress(KeyPressEvent event) {
    if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
        // Event
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!