Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to child components?

I have a JPanel with a grid of JLabels added. I'd like a MouseListener to listen for MouseEvents, but the JLabels seem to be in the way and no MouseEvent fires when clicking in the location where a JLabel is located.

Is there a relient way to listen to the MouseEvents of a component's children?

like image 531
Lucas Avatar asked Feb 23 '23 08:02

Lucas


1 Answers

MouseEvents are dispatched to the top-most (in z-order) component that is enabled for them, that has a mouseListener registered on it or internally has set the eventMask to handle them. While typically a JLabel is transparent (and thus the events should reach the underlying panel), they might get event-opaque by f.i. setting a tooltip.

In jdk 7, you can use a JLayer to get hold of all (mouse) events delivered to its children. The documentation of JLayer says:

JLayer is a good solution if you only need to do custom painting over compound component or catch input events from its subcomponents.

It's predecessor for jdk6 is the JXLayer project in SwingLabs. Yet another option is to use an AWTEventListener, as described in Rob's blog (beware: might not be allowed in security restricted contexts)

like image 147
kleopatra Avatar answered Mar 05 '23 03:03

kleopatra