我想要发生的是当鼠标位于绿色矩形上方时,我希望绿色矩形变为红色,但即使输出显示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;
}
}
}
答案 0 :(得分:1)
您只是将变量设置为红色,但这不会将矩形的颜色更改为红色。为了实现 ,您必须再次在矩形上调用setColor
方法:
playColor = Color.RED;
drawStartScreen(g);
答案 1 :(得分:0)
您将变量设置为红色,而不是矩形。您需要再次在矩形上调用setColor
。