java 阻止事件在 GWT 中冒泡
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/214262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop a event from bubbling in GWT
提问by Stephen Cagle
I have the following snippet of code, changeTextArea is a TextArea object.
我有以下代码片段,changeTextArea 是一个 TextArea 对象。
changeTextArea.addKeyboardListener(new KeyboardListenerAdapter()
public void onKeyPress( Widget sender, char keyCode, int modifier){
//do something
//I WISH TO STOP THE EVENT THAT MAPS TO THIS KEYPRESS FROM BUBBLING ANY FURTHER
}
}
How would I stop the Event that is causing this method to be called from bubbling up from changeTextArea into the Panels/Widgets/Composites/Whatever that contain changeTextArea. Put succinctly, how do I stop it from bubbling any further. Any help would be appreciated (especially code samples).
我将如何阻止导致调用此方法的事件从 changeTextArea 冒泡到包含 changeTextArea 的面板/小部件/复合材料/任何内容。简而言之,我如何阻止它进一步冒泡。任何帮助将不胜感激(尤其是代码示例)。
回答by rustyshelf
As far as I know you can't do it via a keyboard listener, but it is possible by adding an event preview using the DOM class:
据我所知,您无法通过键盘侦听器执行此操作,但可以通过使用 DOM 类添加事件预览来实现:
DOM.addEventPreview(EventPreview preview)
Then when you get the event:
然后当你得到事件时:
onEventPreview(Event event)
You should return false, to say you want to cancel the event. The Event object also supports this method:
您应该返回 false,表示您想取消该事件。Event 对象也支持这个方法:
public final void cancelBubble(boolean cancel)
Cancels bubbling for the given event. This will stop the event from being propagated to parent elements.
取消给定事件的冒泡。这将阻止事件传播到父元素。
You can find more details here: http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html
您可以在此处找到更多详细信息:http: //google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html
回答by jgindin
You can definitely use the Event's cancelBubble() and preventDefault() methods from within any code that has access to the Event. There's no need to have an event preview...
您绝对可以在可以访问事件的任何代码中使用事件的 cancelBubble() 和 preventDefault() 方法。没有必要有一个事件预览...
回答by Sean
You can call the sender's cancelKey() event. Here's an example that will only allow numbers to be inputted, all other keys get rejected.
您可以调用发件人的 cancelKey() 事件。这是一个仅允许输入数字的示例,所有其他键都被拒绝。
private class RowColChangeHandler implements KeyPressHandler {
私有类 RowColChangeHandler 实现 KeyPressHandler {
public void onKeyPress(KeyPressEvent event) {
char keyCode = event.getCharCode();
if(keyCode <48 || keyCode >57)
{
((TextArea)event.getSource()).cancelKey();
}
}
}
回答by guillermo
you could reach it when possible by doing
event.doit = false
你可以在可能的情况下通过这样做来达到它
event.doit = false

