javaswingmouseeventjlayeredpane

Java Swing: how to pass mouse events through JLayeredPane


Can a JLayeredPane pass along mouse events from the top layer to a lower layer?

I have two components inside a JLayeredPane: one JFrame displaying a map, and one JEditorPane displaying HTML text on top of it. The JEditorPane is partially transparent and functions as an overlay, showing text on top of the map but being otherwise invisible.

My problem: when the mouse is moved to the transparent parts of the JEditorPane, the JFrame of the map doesn't get the mouse events.

In JavaFX, the StackPane component has the setPickOnBounds(false) to pass the mouse events to the frames underneath if the mouse if it's over a transparent pixel.

Is there something of the sort in JLayeredPane?


Solution

  • To pass a mouse event e to a component c, use

        c.dispatchEvent(SwingUtilities.convertMouseEvent(e.getComponent(), e, c));
    

    For example, to pass a mouse click event from b to c, use

    b.addMouseListener(
            new MouseAdapter() {
              @Override
              public void mouseClicked(MouseEvent e) {
                c.dispatchEvent(SwingUtilities.convertMouseEvent(b, e, c));
              }
            });