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

时间:2015-07-13 19:32:07

标签: java swing event-handling applet mouseevent

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);
    }
}

我的applet窗口的坐标:

  

左上角 - (0,0)
  左下角 - (0,199)
  右上角 - (349,0)
  右下角 - (349,199)

我的期望:

  1. 当鼠标进入小程序窗口时,应在坐标"Mouse Entered"

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

  4. 实际发生了什么:

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

    例如,鼠标从Lower left cornerLower right corner之间进入applet窗口,比如(187, 199),然后是"Mouse Entered",而不是{{1}显示}},显示在(0, 10)

    我的问题

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

2 个答案:

答案 0 :(得分:2)

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的值。导致它显示鼠标最后位置的坐标。尝试创建一个不同的变量来跟踪鼠标的位置。

答案 1 :(得分:2)

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

您在此处覆盖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);
}