-3

好的,我在变量 C 中设置的颜色等于 coal1 中的变量,但是当通过 if 语句时,它会返回它们不相等。我已经用打印线调试了它,结果对我来说很奇怪。任何帮助将不胜感激!

代码

class MyTask extends TimerTask {

    static Color coal1 = new Color(255, 255, 255);
    Robot robot;
    int xRock, yRock;

    MyTask(Robot r, int x, int y) {
        this.robot = r;
        this.xRock = x;
        this.yRock = y;
    }

    public void run() {
        java.awt.Color c = this.robot.getPixelColor(this.xRock, this.yRock);
        System.out.println("c before the if: "+c);
        System.out.println("coal 1 before the if: "+coal1);

        if (c.equals(coal1)) {  //I can not get the c from the other class to compair with coal1
            System.out.println("color is the same");
        } 
        else {
            System.out.println("c after the if: "+ c);
            System.out.println("coal1 after the if: "+coal1);
            System.out.println("color changed");

            //Stop Timer.
            this.cancel();
        }
    }
}

当我运行它时,我得到

c before the if: java.awt.Color[r=225,g=225,b=225]
coal 1 before the if: java.awt.Color[r=255,g=255,b=255]
c after the if: java.awt.Color[r=225,g=225,b=225]
coal1 after the if: java.awt.Color[r=255,g=255,b=255]
color changed
4

3 回答 3

5

根据您的输出,它们不一样。c的红绿蓝分量为 225,而coal1的分量为 255。

Color.equals(Color o)比较在您的情况下不相同的 RGB 值

于 2013-05-24T18:16:31.703 回答
-1

这是我想出的解决方案:

int R = 255; 
int G = 255; 
int B = 255;
if ((c.getRed() == R) && (c.getGreen() == G) && (c.getBlue() == B)) { 
    System.out.println("Found color"); 
} else { 
    System.out.println("Couldnt find color"); 
} 
于 2013-05-24T18:13:54.833 回答
-3

尝试使用 instanceof 运算符。

于 2013-05-24T18:13:28.567 回答