mouseEntered()和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);
    }
}

我的小程序窗口的坐标:

左上角-(0,0(
左下角-(0199(
右上角-(349,0(
右下角-(349199(

我的期望:

  1. 当鼠标进入小程序窗口时,应在坐标(0, 10) 处显示消息"Mouse Entered"

  2. 当鼠标移动时,状态窗口中应显示一条消息"Moving mouse at mouseX, mouseY"。其中mouseXmouseY是鼠标的当前坐标

实际发生的情况:

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

例如,鼠标从Lower left cornerLower right corner之间进入小程序窗口,例如(187, 199),则消息"Mouse Entered"不是在(0, 10)显示,而是在(187, 199) 显示

我的问题

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

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

您在此处覆盖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);
}
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的值。使其显示鼠标最后位置的坐标。尝试创建一个不同的变量来跟踪鼠标的位置。

相关内容

  • 没有找到相关文章

最新更新