JavaFX 改变 ImageView 的颜色

JavaFX change color of ImageView

您好,我正在尝试在您的鼠标悬停在 ImageView 上时更改它的颜色(悬停)

所以我有一个 css 文件,其中包含:

.cross:hover {
    -fx-background-color: red;
}

这是十字架:

@FXML
    private ImageView cross;

我在fxml文件中设置了fx:id。

现在当我将鼠标悬停在它上面时没有任何反应。

这就是我将样式 sheet 添加到场景中的方式:

scene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm());

这就是我在 ImageView 上为 css 设置 ID 的方式:

cross.getStyleClass().add("cross");

那么,当我将鼠标悬停在 ImageView 上时,如何更改它的颜色?

ImageView 的颜色由图像本身的像素数据定义。您可能需要创建(外部)替代图像,并将 "background" 更改为红色,然后使用 ImageView-fx-image CSS 属性 来更改显示的图像:

.cross {
    -fx-image: url(images/cross.png);
}
.cross:hover {
    -fx-image: url(images/red-cross.png);
}

其中 images 文件夹与 CSS 文件具有相同的父文件夹(参见 CSS docs on URL。)