java JFrame 上的鼠标监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1408080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MouseListener on JFrame
提问by Savvas Dalkitsis
I want to be notified of mouse events (specifically the mouse entered and exited events) on my JFrame. But when i add a mouselistener to it i get the events on the borders of the frame not the entire frame with it's contents.
我想在我的 JFrame 上收到鼠标事件(特别是鼠标进入和退出事件)的通知。但是当我向它添加一个 mouselistener 时,我会在框架的边界上获得事件,而不是整个框架及其内容。
Any ideas as to why?
关于为什么的任何想法?
EDIT : Or at least do you have an alternative? I want a "gloabal" way to catch mouse events on the JFrame. Maybe a mouselistener is not the answer.
编辑:或者至少你有其他选择吗?我想要一种“全局”方式来捕获 JFrame 上的鼠标事件。也许鼠标监听器不是答案。
回答by ykaganovich
You can get all events and check if their source is a component in the JFrame.
您可以获取所有事件并检查它们的来源是否是 JFrame 中的组件。
回答by SingleShot
There is an invisible component that overlays the whole GUI, the "glass pane". You can attach your listeners to that. Example:
有一个不可见的组件覆盖了整个 GUI,即“玻璃窗格”。你可以将你的听众附加到它上面。例子:
JFrame frame = new JFrame();
Component glassPane = frame.getGlassPane();
glassPane.addMouseListener(myListener);
If you want your intercepted events to pass through to the underlying components, you can redispatch them. For example:
如果您希望拦截的事件传递到底层组件,则可以重新调度它们。例如:
public void mouseMoved(MouseEvent e) {
redispatchMouseEvent(e, false);
}
回答by OscarRyz
Because the contents ( probably a JPanel ) are "shadowing" and consuming the events and they don't reach the JFrame.
因为内容(可能是 JPanel )正在“遮蔽”并消耗事件,而它们没有到达 JFrame。
What you can do is to add the same listener to all the children. There should be a better way though.
您可以做的是为所有孩子添加相同的侦听器。不过应该有更好的方法。
回答by Tom Hawtin - tackline
An alternative to AWTEventListeneris to push an EventQueue. This has the advantage that applets and WebStart application can do this.
另一种方法AWTEventListener是推送一个EventQueue. 这样做的好处是小程序和 WebStart 应用程序可以做到这一点。

