Search code examples
javaeventsswing

Java event propagation stopped


I have a main window:

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

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

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.

How do I stop the event from being consumed by the child?


Solution

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

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