简体   繁体   中英

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?

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 fi 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM