Java事件传播停止 [英] Java event propagation stopped

查看:157
本文介绍了Java事件传播停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主窗口:

public class MainPanel extends JFrame implements MouseListener {

   public MainPanel() {
      setLayout(new FlowLayout());
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      addMouseListener(this);

      ChildPanel child = new ChildPanel();
      add(child);

      JPanel spacer = new JPanel();
      spacer.setPreferredSize(new Dimension(50, 50));
      add(spacer);

      pack();
      setLocationRelativeTo(null);
   }

   @Override
   public void mouseClicked(MouseEvent e) {
      System.out.println("Mouse click event on MainPanel");
   }
}

还有一个孩子JPanel:

And a child JPanel:

public class ChildPanel extends JPanel implements MouseListener {

   public ChildPanel() {
      setBackground(Color.RED);
      setPreferredSize(new Dimension(200, 200));
      //addMouseListener(this);
   }

   @Override
   public void mouseClicked(MouseEvent e) {
      System.out.println("Mouse click event on ChildPanel");
   }
}

通过调用 addMouseListener 在子面板中注释掉,当我点击窗口中的任何位置(包括孩子)时,父点击事件。如果我取消了该呼叫的注释并单击子面板,只有,孩子会收到点击事件,并且不传播到父节点。

With the call to addMouseListener commented out in the child panel, the parent receives click events when I click anywhere in the window, including on the child. If I uncomment that call and click on the child panel, only the child receives the click event and it doesn't propagate to the parent.

如何阻止孩子被消费?

推荐答案

我不认为你可以。我相信这是一个Swing设计原则,只有一个组件接收到一个事件。

I don't think you can. I believe it's a Swing design principle that only one component receives an event.

然而,您可以获得所需的行为,但通过 JFrame ChildPanel 并调用其 mouseClicked(MouseEvent)或任何您想要的方法。或者只是得到父组件。

You can get the behavior you want, however, but pass the JFrame to the ChildPanel and calling its mouseClicked(MouseEvent) or whatever method you want. Or just get the parent component.

   @Override
   public void mouseClicked(MouseEvent e) {
      System.out.println("Mouse click event on ChildPanel");
      this.frame.mouseClicked(e);
      getParent().mouseClicked(e);
   }

这篇关于Java事件传播停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆