0

我想要发生的是当鼠标悬停在绿色矩形上时,我希望绿色矩形变为红色,但即使输出显示 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;
        }
    }
}
4

2 回答 2

1

您只是将变量设置为红色,但这不会将矩形的颜色更改为红色。为了实现这一点setColor,您必须在矩形上再次调用该方法:

playColor = Color.RED;
drawStartScreen(g);
于 2012-10-28T01:03:37.617 回答
0

您将变量设置为红色,而不是矩形。您需要setColor在矩形上再次调用。

于 2012-10-28T00:44:42.410 回答