是否可以将数组中的索引与颜色进行比较?

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

我正在尝试编写棋盘游戏代码,并使用 for 循环创建了棋盘。就目前而言,我可以单击一个矩形并能够更改其颜色。现在我想把它放在哪里,如果我单击一个特定颜色的矩形将其更改为特定颜色。例如,如果它是蓝色的,那么就把它变成灰色。但是我收到错误 Unlikely argument type for equals(): Color seems to be unrelated to Rectangle 并且我的方块变成了黑色。这是我的代码。谢谢。

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

我还应该提到在创建数组时我这样做:r.setFill(Color.BLUE);

通过调用

r.equals(Color.BLUE)

您正在尝试将矩形实例与 Color 类型进行比较。查看Rectangle的API,其equals-method描述如下:

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.

相反,您需要通过调用

来比较矩形的实际颜色

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

(参见 Post

希望能帮到你。