当游标在子组件上时,JPanel不会生成MouseEvents [英] JPanel does not generate MouseEvents when cursor is on child components

查看:174
本文介绍了当游标在子组件上时,JPanel不会生成MouseEvents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我而言有点奇怪,但是当游标在子组件上时,JPanel不会生成MouseEvents:JTextField和JToolBar,但是当游标在JLabel上时,它会生成MouseEvents。有人可以解释一下为什么吗有没有办法强制JPanel生成事件,即使鼠标在子组件上?

解决方案

事件调度程序将转发鼠标事件到 Container 中的包级别 getMouseEventTarget 方法返回的组件注册的监听器。这将在您的 JFrame 上调用,并且正如JavaDoc所示:


获取有兴趣接收鼠标事件的最高(最深)的轻量级组件。


事件调度程序然后占用此顶部最近的组件(例如你的 JTextField ),只发送事件到所有的监听器。他们这样做是为了避免将这些事件广播到可能在Swing容器内分层的所有组件。 MouseEvents,你可以想像,是非常聊天,所有的 mouseEntered mouseDragged mouseMoved 为所有 MouseListener MouseMotionListener 执行潜在的调度事件在那里查找所有侦听器,然后在层次结构中对所有侦听器发送事件的处理将是耗时的。



假设类似于 JTextField JButton 等,默认的鼠标处理是所有需要的。如果要处理不同的鼠标操作(即,在 mouseEntered / mouseExited )上更改颜色,则可以添加 MouseListener 到你需要的这些小部件。



对于您的处理,我建议您只需将 JPanel 添加为 MouseListener 到您的顶级组件,如果您需要处理这些事件。


It is a bit strange for me but JPanel does not generate MouseEvents when cursor is on child components: JTextField and JToolBar but it generates MouseEvents when cursor is on JLabel. Could someone explaind me why? Is there any way to force JPanel to generate events even if mouse is on child components?

解决方案

The event dispatcher will forward mouse events to the listeners registered to the component that is returned by the package-level getMouseEventTarget method in Container. This will be called on your JFrame, and, as the JavaDoc indicates, it:

Fetchs the top-most (deepest) lightweight component that is interested in receiving mouse events.

The event dispatcher then takes this top-most component (your JTextField, for example) and sends events to all of its listeners only. They do this in order to avoid having to broadcast these events to all of the components that may be layered within a Swing container. MouseEvents, as you can imagine, are very chatty, what with all of the mouseEntered, mouseDragged, and mouseMoved events that are dispatched for all of the MouseListener and MouseMotionListener implementations potentially out there. The processing to find all listeners and then fire events to all of them in the hierarchy would be time consuming.

The assumption is also that for classes like JTextField and JButton, etc., the default mouse handling is all that one would need. If you want to handle mouse actions differently (ie, changing color on a mouseEntered/mouseExited), you can add a MouseListener to these widgets as you need to.

For your processing, I would suggest simply adding your JPanel as a MouseListener to your top level components if you need to handled these events.

这篇关于当游标在子组件上时,JPanel不会生成MouseEvents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆