mouseEntered() 和 mouseMoved() 之间的混淆

Confusion between mouseEntered() and mouseMoved()

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
    String msg = "";                        // I am not implementing those methods which
    int mouseX = 0, mouseY = 0;             // are not related to my question

    public void init()
    {
        addMouseListener(this);
        addMouseMotionListener(this);
    }

    public void mouseEntered(MouseEvent me)
    {
        mouseX = 0;
        mouseY = 10;
        msg = "Mouse Entered";
        repaint();
    }

    public void mouseMoved(MouseEvent me)
    {
        mouseX = me.getX();
        mouseY = me.getY();
        showStatus("Moving mouse at "+mouseX+", "+mouseY);
    }

    public void paint(Graphics g)
    {
        g.drawString(msg, mouseX, mouseY);
    }
}

我的小程序坐标window:

Upper left corner - (0, 0)
Lower left corner - (0, 199)
Upper right corner - (349, 0)
Lower right corner - (349, 199)

我的期望:

  1. 当鼠标进入小程序window时,在坐标(0, 10)

  2. 处应显示一条消息"Mouse Entered"
  3. 当鼠标移动时,状态window中应该显示一条消息"Moving mouse at mouseX, mouseY"。其中mouseXmouseY是鼠标当前坐标

实际发生了什么:

消息 "Mouse entered" 未显示在坐标 (0, 10) 处,而是显示在鼠标进入小程序的初始坐标处 window***

比如鼠标从Lower left cornerLower right corner之间进入小程序window,说(187, 199),然后是消息"Mouse Entered",而不是显示在 (0, 10),显示在 (187, 199)

我的问题

尽管在 mouseEntered() 中指定了 mouseX = 0mouseY = 10,为什么消息 "Mouse Entered" 显示在鼠标进入小程序的坐标 window,但不在坐标 (0, 10) 处?

public void mouseMoved(MouseEvent me)
{
    mouseX = me.getX();
    mouseY = me.getY();
    showStatus("Moving mouse at "+mouseX+", "+mouseY);
}

只要您移动鼠标,mouseMoved 部分中的代码就会更新。因此,它显示 mouseX 和 mouseY 而不是 (0,10) 的原因是因为您在 mouseMoved 方法中更改了 mouseX 和 mouseY 的值。使其显示鼠标最后位置的坐标。尝试创建一个不同的变量来跟踪鼠标的位置。

当您将鼠标移到查看窗格上时,查看窗格会经常重绘。

您在此处覆盖了 mouseXmouseY 的值:

public void mouseMoved(MouseEvent me)
{
    mouseX = me.getX();
    mouseY = me.getY();
    showStatus("Moving mouse at "+mouseX+", "+mouseY);
}

这会导致在您移动鼠标时在这些坐标处进行重绘。如果你想让mouseEntered不动,你可以使用局部变量,例如

public void mouseMoved(MouseEvent me)
{
    int currentMouseX = me.getX();
    int currentMouseY = me.getY();
    showStatus("Moving mouse at "+currentMouseX+", "+currentMouseY);
}