java - 如何检测鼠标指针是否在对象的边界内?

标签 java mouseevent mouselistener

我正在尝试为我的程序制作自己的组件,例如按钮和其他东西,但我似乎无法让 MouseEvent 正常工作。我希望能够检测鼠标指针是否在组件的范围内,并且我的方法由于某种原因总是返回 false。

这是我尝试过的示例:

public void mousePressed(MouseEvent e) {

    for (MyComponent component : components) {

        // getBounds() returns a Rectangle.
        if (component.getBounds().contains(e.getX(), e.getY())) {
            System.out.println("PRESSED");
        }

    }

}

另一个例子:

public void mouseEntered(MouseEvent e) {

    for (MyComponent component : components) {

        boolean isWithinBounds = isWithinBounds(e.getX(), e.getY(), component);

        if (isWithinBounds) {

            component.mouseEntered(e);

        }

    }

}

private boolean isWithinBounds(int x, int y, MyComponent component) {

    // getBounds() returns a Rectangle.
    if (x >= component.getBounds().x
            && x <= component.getBounds().x + component.getBounds().width
            && y >= component.getBounds().y
            && y <= component.getBounds().y + component.getBounds().height) {

        return true;

    } else {

        return false;

    }

}

有谁知道为什么这不起作用以及我应该如何做?

提前致谢!

最佳答案

You should add a mouse listener and react to the mouseEntered-Event:

JFrame.addMouseListener( new MouseAdapter() {

     public void mouseEntered( MouseEvent e ) {
        // your code here
     }
} );

也许有帮助: Finding if my mouse is inside a rectangle in Java

关于java - 如何检测鼠标指针是否在对象的边界内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35683403/

相关文章:

java - 使用 Jsoup 解析 HTML,出现异常

java - 单击折线图上的点时获取值

javascript - Vue.js 在悬停时更改子组件的 css 样式

java - 无法让 MouseListener 工作

java - Swing:MouseListener 仅在 ImageIcon 上而不是 JLabel 上

java - 使用 throw/catch 的鼠标监听器 (java)

java - 生成比数组长度更长的所有可能组合

java - Jenkins 中的集成测试

java - 在 arrayList 的某个索引处插入元素的运行时间是多少?

java - 访问 MouseListener 外部的方法