JavaFX 根据单元格值设置单元格颜色

JavaFX set cell colour depending on cell Value

大家好我想知道是否有一种方法可以根据单元格的值在 javaFX 中的 table 中设置单元格的颜色。

我知道有一种方法,但您必须遍历列。

是否存在像 cell.setColor(GREEN) 或带有 css 文件的函数?

您好, 通常你无法获取 table 单元格的实例,因此你需要创建自定义 TableCell class,并且你可以编写一些如下所述的代码以根据你指定的条件进行更改。以下是如何根据条件更改样式的示例。您需要在代码中覆盖名为 updateItem() 的方法。别忘了。

@Override
protected void updateItem(Integer item, boolean empty) {
    super.updateItem(item, empty);

    if (item == null || empty) {
        setText(null);
        setStyle(""); // set cell style
    } else {
        if (checkCondition) {
            setTextFill(Color.CHOCOLATE);
            setStyle("-fx-background-color: red;");// set your css style here if condition is true
        } else {
            setTextFill(Color.BLACK);
            setStyle(""); // reset the style if condition is false.
        }
    }
}