简体   繁体   English

如何将mouseListener添加到graphics2D矩形

[英]How to add a mouseListener to a graphics2D rectangle

I would like to make a mouseListener that would trigger every time the mouse hovers over a rectangle (or some coordinates on the window). 我想制作一个mouseListener,它将在每次鼠标悬停在矩形(或窗口上的某些坐标)上时触发。 I thought about using mouseEntered but that only triggers when you move your mouse on the screen, not a rectangle etc (Heres what I tried 我曾考虑过使用mouseEntered,但这只会在您在屏幕上移动鼠标时触发,而不是在矩形等位置触发(这里我尝试了

public void mouseEntered(MouseEvent e) {
    int mx = e.getX();
    int my = e.getY();

    if(mx >= 1000 / 2 && mx <= 1000 / 2 + 380) {
        if(my >= 300 && my <= 390) {
            System.out.println("test");
        }
    }

}

) but of course, that didn't work. ),但那当然没有用。 I know that there's probably a question like this, but I couldn't find it and I couldn't find anything that fit my question exactly. 我知道可能存在这样的问题,但是我找不到它,也找不到与我的问题完全相符的东西。

EDIT: I realized that mousEntered was wrong and its actually mouseMoved! 编辑:我意识到mousEntered是错误的,并且实际上是mouseMoved! Heres the code: 这是代码:

public void mouseMoved(MouseEvent e) {
    int mx = e.getX();
    int my = e.getY();

    if(mx >= 1000 / 2 && mx <= 1000 / 2 + 380) {
        if(my >= 300 && my <= 390) {
            System.out.println("test");
        }
    }
}

Take a look at this: 看看这个:

https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

And this: 和这个:

mouseEntered will not execute mouseEntered将不会执行

You should find some helpful notes and answers! 您应该找到一些有用的注释和答案! Also, try printing out "mx" and "my" to the console to make sure that you have the right coordinates. 另外,尝试在控制台上打印“ mx”和“ my”,以确保坐标正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM