Search code examples
javaswingjpaneljlayeredpane

Interact with JPanel behind JLayeredPane


I have been working with Java's swing library a lot recently and I have landed upon another question.

I have a transparent JLayeredPane which sits on top of a JPanel. I need to interact with the JPanel (with a mouse listener) but since I added the JLayeredPane I cannot interact with the JPanel.

As a side note, I pack my JFrame which I would like to pack around the JPanel and not the JLayeredPane but the JLayeredPane seems to take priority now.

Example - Keep in mind there is actually content on the panels, this is just for example.

public Main()
{
    // Main JPanel
    JPanel mainPanel = new JPanel();
    add(mainPanel, BorderLayout.CENTER);

    // JLayeredPane
    add(new JLayeredPane(), BorderLayout.CENTER);

    // Add Mouse Listener
    mainPanel.addMouseListener(new CustomMouseListener());
}

Solution

  • Keep in mind there is actually content on the panels,

    The MouseListener should be added to the panel added to the layered pane, not the panel containing the layered pane.