Momo Momo - 4 months ago 9
Java Question

Preventing components below panel to get hovered when panel is transparent

I have a

JPanel
, set to be transparent:

public SomePanel() {
setOpaque(false);
[...]
}


I have other
JComponent
instances under it (at the same location, but below it).

If I draw on the panel using
paintComponent(g)
, putting my mouse on the panel still triggers
mouseEntered
and
mouseExited
events for other components below it.

How can I prevent components below the panel to fire mouse events if the non-opaque panel is visible? I am using
setOpaque(false)
because I need a transparent background, perhaps there is another way to achieve this?

Answer

One possible solution: give the covering JPanel its own MouseListener, one that is there to simply swallow the mouse events and prevent them from being transmitted. The code could be as simple as:

myPanel.addMouseListener(new MouseAdapter() {});
Comments