在JPanel上的任何位置检测鼠标进入/退出事件 [英] Detecting mouse enter/exit events anywhere on JPanel

查看:131
本文介绍了在JPanel上的任何位置检测鼠标进入/退出事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,当鼠标进入JPanel区域并退出JPanel区域时,我想知道一个JPanel。所以我添加了一个鼠标监听器,但是如果JPanel上有组件并且鼠标经过其中一个组件,则它被检测为JPanel上的一个出口,即使该组件位于JPanel上。我想知道是否有人知道如何解决这个问题而不做像在JPanel上的所有组件上添加监听器那样的东西?

Basically there is a JPanel on which I want to know when the mouse enters the area of the JPanel and exits the area of the JPanel. So I added a mouse listener, but if there are components on the JPanel and the mouse goes over one of them it is detected as an exit on the JPanel, even though the component is on the JPanel. I was wondering whether anyone knows any way to solve this problem without doing something like adding listeners onto all components on the JPanel?

推荐答案

有一个非常简单的解决方案可以解决这个问题:

There is a very easy solution for this problem that can work :

public class MyJPanel implements MouseListener {

    public void mouseExited(MouseEvent e) {
        java.awt.Point p = new java.awt.Point(e.getLocationOnScreen());
        SwingUtilities.convertPointFromScreen(p, e.getComponent());
        if(e.getComponent().contains(p)) {return;}
        ...//the rest of your code
    }

    ...
}

这样你只需忽略mouseExited事件就会发生在子元素上。

This way you just ignore the mouseExited event when it occurs on a child element.

这篇关于在JPanel上的任何位置检测鼠标进入/退出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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