简体   繁体   English

如何听儿童组件?

[英]How to listen to child components?

I have a JPanel with a grid of JLabels added. 我有一个添加了JLabels网格的JPanel 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. 我想要一个MouseListener来监听MouseEvents ,但是JLabels似乎MouseEvents ,当点击JLabel所在的位置时没有MouseEvent触发。

Is there a relient way to listen to the MouseEvents of a component's children? 是否有一种方便的方式来监听组件子项的MouseEvents

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. MouseEvents被分派到为它们启用的最顶层(按z顺序)组件,其上注册了mouseListener或在内部设置了eventMask来处理它们。 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. 虽然通常JLabel是透明的(因此事件应该到达底层面板),但是通过设置工具提示,它们可能会使事件不透明。

In jdk 7, you can use a JLayer to get hold of all (mouse) events delivered to its children. 在jdk 7中,您可以使用JLayer来获取传递给其子级的所有(鼠标)事件。 The documentation of JLayer says: JLayer的文档说:

JLayer is a good solution if you only need to do custom painting over compound component or catch input events from its subcomponents . 如果您只需要对复合组件进行自定义绘制或从子组件捕获输入事件,则JLayer是一个很好的解决方案。

It's predecessor for jdk6 is the JXLayer project in SwingLabs. 它的前身是jdk6,是SwingLabs中的JXLayer项目 Yet another option is to use an AWTEventListener, as described in Rob's blog (beware: might not be allowed in security restricted contexts) 另一种选择是使用AWTEventListener,如Rob的博客中所述 (注意:在安全限制的上下文中可能不允许)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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