Is it possible to compare an index in an array to a color?

I’m trying to code a board game and have created the board with for loops. As it stands now I can click a rectangle and am able to change its color. Now I want to have it where if I click a rectangle that is a certain color to change it to a specific color. For example iff it’s blue then make it grey. However I get the error Unlikely argument type for equals(): Color seems to be unrelated to Rectangle and my squares turn black instead. Here is my code. Thank you.

public void game (MouseEvent eventGame) {
    for(Rectangle r: rectangles) {
        if (r.equals(Color.BLUE)) {
            r.setOnMouseClicked(event->{
                r.setFill(Color.GREY);
            });
        } else { r.setOnMouseClicked(event->{
                r.setFill(Color.BLACK);
            });}
    }
}

I should also mention when creating the Array I do this: r.setFill(Color.BLUE);.

Answer

By calling

r.equals(Color.BLUE)

you are trying to compare a rectangle instance with a Color type. Looking at the API of Rectangle, its equals-method is described as follows:

Checks whether two rectangles are equal. The result is true if and only if the argument is not null and is a Rectangle object that has the same upper-left corner, width, and height as this Rectangle.

Instead you need to compare the actual Color of the rectangle by calling

r.getFill().equals(Color.WHITE)

(see Post Can you return the color of a rectangle object in java?)

Hope, I could help you.

Leave a Reply

Your email address will not be published. Required fields are marked *