我想得到我的JFrame的鼠标位置。但是,当鼠标在其子组件上时(例如表,添加到JFrame中的按钮),MouseMotion事件将不再监听。我怎样才能得到鼠标的位置?
发布于 2013-08-22 08:46:46
假设您的注释中的用例是要解决的真正问题,那么解决方法就是实现mouseExited,这样它就可以检查鼠标是否还在框架的某个位置,并且只有在没有的情况下才能隐藏它。
类似于:
MouseListener closer = new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
Rectangle r = new Rectangle(sideBar.getSize());
if (!r.contains(e.getPoint())) {
sideBar.setVisible(false);
}
}
};发布于 2013-08-22 12:44:14
我试图在我的Swing应用程序上创建一个边栏,侧边栏是一个未修饰的JFrame。我已经设置好在鼠标退出时释放它。但是当我将鼠标移动到添加到侧栏的组件上时,它就消失了。想法可能是愚蠢的--我是Java新手。
您可以像kleopatra建议的那样实现mouseExited,但类似于这样做:
MouseListener closer = new MouseAdapter() {
public void mouseExited(MouseEvent e) {
// obtain source frame and see if mouse has left it
Container cnt;
if (e.getSource() instanceof JFrame) {
// our frame, no conversion needed
cnt = (Container) e.getSource();
} else {
// inside a descendant
cnt = SwingUtilities.getAncestorOfClass(
JFrame.class, e.getComponent());
// convert mouse event to make it appear
// as if the frame generated it (I think :D)
e = SwingUtilities.convertMouseEvent(
e.getComponent(), e, (Component) cnt);
}
Rectangle r = new Rectangle(cnt.getSize());
if (!r.contains(e.getPoint())) {
cnt.setVisible(false);
// or whatever
}
}
};这是为您的侧栏及其自身的所有后代组件设置的。它应该检查你的鼠标是否还在你的侧边栏里,不管鼠标在哪个子代/后代上盘旋。
您还应该考虑使用未修饰的JDialog而不是JFrame。
您的侧边栏正在消失的原因可能是您只向它添加了一个鼠标侦听器,而没有添加到它的任何一个子类。这可能有违直觉,但当鼠标指针进入侧栏的子/后代时,将为侧栏生成一个mouseExited事件,然后为鼠标输入的任何子/后代生成一个mouseEntered事件。这就是Swing鼠标事件是如何被设计成工作的,而且你没有什么可以做的。
https://stackoverflow.com/questions/18373337
复制相似问题