本文介绍了颜色等于另一种颜色,Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,我在变量C中设置的颜色等于在coal1中的变量,但是当通过一个if语句时,它回到它们不相等。我已经用打印线调试它,结果是我奇怪的。任何帮助将非常感谢!



代码

  class MyTask extends TimerTask {

static Color coal1 = new Color(255,255,255);
机器人机器人;
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:+ c);
System.out.println(coal 1 before the:+ coal1);

if(c.equals(coal1)){//我不能得到c从另一个类到compair with coal1
System.out.println(color is the same );
}
else {
System.out.println(c后的if:+ c);
System.out.println(coal1 after:+ coal1);
System.out.println(color changed);

//停止计时器。
this.cancel();
}
}
}
  c在if:java.awt.Color [r = 225,g = 225,b = 225] 
煤1前的if:java.awt.Color [r = 255,g = 255,b = 255]
c之后if:java.awt.Color [r = 225,g = 225,b = 225 ]
coal1 after:java.awt.Color [r = 255,g = 255,b = 255]
颜色已更改


解决方案

根据你的输出,他们是不一样的。 c 的红色,绿色和蓝色组件为225,而 coal1 的组件为255。 >

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


Okay the color I have set in the variable C is equal to the variable in coal1, but when put through an if statement it comes back that they are not equal. I've debugged it with print lines and the result is weird to me. Any help would be greatly appreciated!

Code

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

When I run it i get

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
解决方案

According to your output, they are not the same. c's red, green, and blue components are 225, while coal1's components are 255.

Color.equals(Color o) compares the RGB values which in your case are not the same

这篇关于颜色等于另一种颜色,Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 10:02