Java event propagation stopped

后端 未结 2 1121
暗喜
暗喜 2020-12-07 01:48

I have a main window:

public class MainPanel extends JFrame implements MouseListener {

   public MainPanel() {
      setLayout(new FlowLayout());
      setD         


        
相关标签:
2条回答
  • 2020-12-07 02:22

    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);
       }
    
    0 讨论(0)
  • 2020-12-07 02:29

    In Swing, you generally want the clicked component to respond; but you can forward the mouse event to the parent, as shown below. Here's a related example.

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    /** @see https://stackoverflow.com/questions/3605086 */
    public class ParentPanel extends JPanel {
    
        public ParentPanel() {
            this.setPreferredSize(new Dimension(640, 480));
            this.setBackground(Color.cyan);
            this.addMouseListener(new MouseAdapter() {
    
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println("Mouse clicked in parent panel.");
                }
            });
            JPanel child = new JPanel();
            child.setPreferredSize(new Dimension(320, 240));
            child.setBackground(Color.blue);
            child.addMouseListener(new MouseAdapter() {
    
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println("Mouse clicked in child panel.");
                    ParentPanel.this.processMouseEvent(e);
                }
            });
            this.add(child);
        }
    
        private void display() {
            JFrame f = new JFrame("MouseEventTest");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(this);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new ParentPanel().display();
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题