gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:07:28 24 4
gpt4 key购买 nike

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

我的小程序窗口的坐标:

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

我的期望:

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

    处显示消息 "Mouse Entered"
  2. 当鼠标移动时,状态窗口中应显示消息“Moving mouse at mouseX, mouseY”。其中mouseXmouseY为鼠标当前坐标

实际发生了什么:

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

例如,鼠标从左下角右下角之间进入小程序窗口,比如说(187, 199),然后消息 "Mouse Entered" 不是显示在 (0, 10),而是显示在 (187, 199)/p>

我的问题

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

最佳答案

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

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

关于java - mouseEntered() 和 mouseMoved() 之间的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31391869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com