Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java2D: if statement doesn`t work with java.awt.Color

Tags:

java

java-2d

I have a getPixelColour function:

Color getPixelColor(int x, int y) {
    if(mazeImage == null) System.out.println(":(");
    int pixel = mazeImage.getRGB(x, y);
    int  red = (pixel & 0x00ff0000) >> 16;
    int  green = (pixel & 0x0000ff00) >> 8;
    int  blue = pixel & 0x000000ff;
    return new Color(red,green,blue);
}

For example a pixel is black, and System.out.println(getPixelColor(x,y) + " " + Color.BLACK); writes java.awt.Color[r=0,g=0,b=0] java.awt.Color[r=0,g=0,b=0]

But getPixelColor(x,y) == Color.BLACK returns false. What's wrong with it?

like image 460
DarkSun Avatar asked Jul 27 '26 06:07

DarkSun


2 Answers

You are comparing two different Color objects which will return false (i.e., two different objects at different memory locations).

If you wish to properly compare them, use equals():

getPixelColor(x, y).equals(Color.BLACK);
like image 197
Simeon Visser Avatar answered Jul 29 '26 20:07

Simeon Visser


Instead of using getPixelColor(x, y) == Color.BLACK try Color.BLACK.equals(getPixelColor(x, y))

You should also read up on the equals method in Java and when it is appropriate to use it vs. the == operator.

like image 40
darrengorman Avatar answered Jul 29 '26 20:07

darrengorman