拦截或委托具有重叠组件的事件
我有两个大小相等的 JPanel
,一个在另一个的顶部。顶层用作拖动选择面板,另一层添加了其他组件。我的问题是这些添加的组件的鼠标事件处理程序不会被触发,因为它们是由覆盖面板处理的。我怎样才能仍然拖动这些添加的组件的顶部,但仍然为底层组件启用 mouseEntered
和 mouseExited
?
这是屏幕截图:
如您所见,选择矩形绘制在覆盖的 JPanel
上,但就好像我的鼠标无法穿过这个面板来查看下面的内容(寻找更好的方法来解释这一点)。
I have two JPanels
equal in size, one over the top of the other. The top layer serves as a drag selection panel, and the other one has other components added to it. My problem is that the mouse event handlers of these added components aren't triggered, because they are handled by the overlaying panel instead. How can I still drag over the top of these added components, but still have mouseEntered
and mouseExited
enabled for the underlaying components?
Here is a screenshot:
As you can see, the selection rectangle is painted on the overlaying JPanel
, but it's as if my mouse can't get through this panel to see what's underneath (in search of a better way to explain that).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重新发明轮子的另一种方法是使用 JLayer(jdk7 的新功能,可在 SwingLabs 子项目 JXLayer 中用于 jdk6) :
下面是一个简单的示例 - 只是为了演示其用法,逻辑显然不完整:) - 使用 mouseEvents 跨越橡皮筋
示例使用片段:
An alternative to re-inventing the wheel is using JLayer (new to jdk7, available for jdk6 in the SwingLabs subproject JXLayer):
Below is a quick example - just to demonstrate its usage, logic obviously incomplete :) - of spanning a rubberband with mouseEvents
Sample usage snippet:
不要使用覆盖面板。我在您上一篇文章中就如何做到这一点提出了建议。
或者,如果您确实使用覆盖面板,则只需使用它进行绘图,并让底层面板侦听鼠标事件,然后调用覆盖面板上的重绘。
编辑:
也许更好的方法是在各个组件上使用 MouseListener,然后处理矩形的绘制,您可以使用 全局事件监听器 用于监听 mousePressed、mouseDragged、mouseReleased 事件。您需要检查每个事件的来源,以查看来源是否是面板本身或面板上的组件。您可以使用
SwingUtilities.isDescendingFrom(...)
来帮助完成第二个测试。Don't use an overlaying panel. I gave a suggestion in your last posting on how you might do this.
Or, if you do use an overlaying panel, then just use it for drawing and have the underlying panel listen for the mouse events and then invoke the repainting on the overlaying panel.
Edit:
Maybe a better approach is to use a MouseListener on the individual components and then to handle the drawing of the rectangle you can use a Global Event Listener to listen for the mousePressed, mouseDragged, mouseReleased event. You would need to check the source of each event to see if the source was the panel itself oa component on the panel. You can use
SwingUtilities.isDescendingFrom(...)
to help with this second test.