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)
左下角 - (0,199)
右上角 - (349,0)
右下角 - (349,199)
当鼠标进入小程序窗口时,应在坐标"Mouse Entered"
(0, 10)
当鼠标移动时,状态窗口中应显示消息"Moving mouse at mouseX, mouseY"
。其中mouseX
和mouseY
是鼠标的当前坐标
消息"Mouse entered"
未显示在坐标(0, 10)
处,而是显示在鼠标进入小程序窗口的初始坐标处***
例如,鼠标从Lower left corner
和Lower right corner
之间进入applet窗口,比如(187, 199)
,然后是"Mouse Entered"
,而不是{{1}显示}},显示在(0, 10)
尽管在(187, 199)
中指定了mouseX = 0
和mouseY = 10
,为什么消息mouseEntered()
会显示在鼠标进入小程序窗口的坐标处,但是不在坐标"Mouse Entered"
?
答案 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)
当您将鼠标移到其上时,查看窗格会经常重绘。
您在此处覆盖mouseX
和mouseY
的值:
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);
}