如何防止 onclick 事件传播到 Vaadin 中的子元素?

How to prevent the propagation of an onclick event to a child element in Vaadin?

我需要当我点击一个图像元素时执行一个事件,而另一方面,当我点击 UI.getCurrent() 元素时另一个不同的事件被执行

我在 UI 元素中有一个 AbsoluteLayout (leftLayout),其中包含图像。

实际上,当我点击图片时,触发了两个事件:显示 "Game Over" 通知并在其下方出现 "Good" 通知。

如何防止 onclick UI.getCurrent() 事件传播到图像元素?

public class VaadinmatchinggameUI extends UI{
   //...
   private AbsoluteLayout leftLayout = new AbsoluteLayout();
   ///...
    @Override
    protected void init(VaadinRequest request) {
     //...
     UI.getCurrent().addClickListener(new ClickListener() {

        @Override
        public void click(ClickEvent event) {
            Notification.show("Game Over");
        }
    }); 
     addImg();
    }
    private void addImg() {
      //...
      FileResource resource = new FileResource(new File(PATH));
      Image face = face = new Image(null, resource);
      leftLayout.addComponent(face, "top:" + randomTop 
                    + "px; left:" + randomLeft + "px;");
      face.addClickListener(new ClickListener() {
            @Override
            public void click(ClickEvent event) {
                Notification.show("Good", Notification.Type.HUMANIZED_MESSAGE);
            }
        });

    }
}

解决方案是在布局上添加点击侦听器,当您捕捉到点击时检查点击位置。

查看下面的代码:

// Listen for layout click events
layout.addListener(new LayoutClickListener() {
 public void layoutClick(LayoutClickEvent event) {

     // Get the child component which was clicked
     Component child = event.getChildComponent();

     if (child == null) {
         // Not over any child component
         getWindow().showNotification(
                 "The click was not over any component.");
     } else {
         // Over a child component
         getWindow().showNotification(
                 "The click was over a "
                         + child.getClass().getCanonicalName());
     }
 }
});

您可以在 link 上找到完整的示例:ClickableLayoutBasicExample.java

此代码已针对 Vaadin 6 进行测试,但稍作修改后也适用于 Vaadin 7。