简体   繁体   English

如何拦截Java GWT中的KeyPressEvent?

[英]How to intercept KeyPressEvent in Java GWT?

I am new to Java and in our code we are using GWT. 我是Java新手,在我们的代码中我们使用GWT。

We are using KeyPressEvent to process the Key_Enter request. 我们使用KeyPressEvent来处理Key_Enter请求。 But it seems, for each enter request, two events fired from KeyPressEvent . 但对于每个输入请求,似乎是从KeyPressEvent触发的两个事件。 But I expect only one event should be fired, since I enter only one time. 但我希望只有一个事件应该被解雇,因为我只进入一次。

The following is my code. 以下是我的代码。 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. 如果我使用event.getCharCode()而不是event.getNativeEvent().getKeyCode() ,它只返回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: 我更喜欢使用KeyUpEvent因为用户无法将其与KeyPressEvent区分开来,所以这是我的解决方案:

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. KeyEventJavaDoc警告说,键盘处理中的浏览器特性没有被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. 本机键盘事件有点混乱(http://www.quirksmode.org/js/keys.html),我们在这里进行一些简单的规范化,但不要尝试任何复杂的修补,因此请警告用户。

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. 阅读http://www.quirksmode.org/js/keys.html以了解更多信息。

Try calling sinkEvents on the widget which tries to listen. 尝试在试图监听的小部件上调用sinkEvents。 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. KeyPressEvent用于产生实际字符代码的按键 - 就像按下'a'键一样。 If you want to be notified when the enter key is pressed use KeyDownEvent instead: 如果您想在按下回车键时收到通知,请使用KeyDownEvent

void onEnter(KeyDownEvent event) {
  if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
    // Handle key press
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM