我想发生的是,当鼠标悬停在绿色矩形上时,我希望绿色矩形变成红色,但是即使输出显示playColor是红色,它也不会变成红色。怎么来的?代码如下:
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class StartScreen implements MouseMotionListener {
int mouseX, mouseY;
Color playColor = Color.GREEN;
public void drawStartScreen(Graphics g) {
g.setColor(playColor);
g.fillRect(200, 200, 100, 100);
System.out.println(playColor);
}
@Override
public void mouseDragged(MouseEvent me) { }
@Override
public void mouseMoved(MouseEvent me) {
mouseY = me.getYOnScreen();
mouseX = me.getXOnScreen();
isMouseover();
}
private void isMouseover() {
System.out.println("x: " + mouseX + "y: " + mouseY);
if (mouseX > 200 && mouseX < 300 && mouseY > 200 && mouseY < 300) {
System.out.println(playColor);
playColor = Color.RED;
}
}
}
最佳答案
您仅将变量设置为红色,但不会将矩形的颜色更改为红色。为此,必须在矩形上再次调用setColor
方法:
playColor = Color.RED;
drawStartScreen(g);