JavaFX :使用 css 为单个树项着色



我希望能够根据某些条件为treeView的各个树项着色。这个答案似乎不错,但我无法实现它。https://stackoverflow.com/a/10931896/6653207

我无法理解如何使用setCellFactory方法来格式化单个TreeItem

我有一堂课

public class Bag {
    public String caption,assignment="";
    Boolean eval;
    public Set<Vertex> Nodes = new HashSet<Vertex>();
    public Vector<Bag> ChildBags = new Vector<Bag>();
     @Override
    public String toString()
    {
        return assignment+ " " +caption;
    }
}

这是我的 css 文件:

.true{
    -fx-text-fill:#33cc00 ;
}
.assignment{
    -fx-text-fill: #0033cc
}

所以我想将 eval 属性为真的所有节点的标题(toString() 方法返回(着色为绿色。toString()方法为所有节点返回的赋值字符串应为蓝色。

我该怎么做?

谢谢。

通过重写TreeCellupdateItem方法,你可以根据单元格所包含TreeItem的值来调整TreeCell的属性。

在下面的示例中,伪类被分配给包含前缀为 "child" 的值的所有单元格,并且所有空单元格都将获得黑色背景。

TreeView<String> treeView = ...
PseudoClass childPseudoClass = PseudoClass.getPseudoClass("child");
treeView.setCellFactory(tv -> new TreeCell<String>() {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            // update for empty cell / cell containing null
            pseudoClassStateChanged(childPseudoClass, false);
            setText("");
            setStyle("-fx-background-color: black;");
        } else {
            // update for filled cell
            pseudoClassStateChanged(childPseudoClass, item.startsWith("child"));
            setText(item);
            setStyle(null);
        }
    }
});

CSS 样式表

.tree-cell:child {
    -fx-background-color: red;
}

每次值更改时,TreeView都会调用 updateItem 方法,例如,如果新TreeItem与单元格关联或修改了TreeItemvalue属性。

您还可以使用工厂将侦听器添加到TreeCell,在返回之前,以防您喜欢这样做,例如想要根据 treeItem 属性更改单元格。


编辑:要对文本应用不同的颜色,您需要对文本部分使用不同的Node

treeView.setCellFactory(tv -> new TreeCell<Bag>() {
    private final Text assignment;
    private final Text caption;
    private final Node graphic;
    {
        assignment = new Text();
        caption = new Text();
        assignment.getStyleClass().add("assignment");
        graphic = new HBox(4, assignment, caption);
        setGraphic(graphic);
    }
    @Override
    protected void updateItem(Bag item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            setGraphic(null);
        } else {
            setGraphic(graphic);
            assignment.setText(item.assignment);
            caption.setText(item.caption);
            caption.getStyleClass().remove("true");
            if (item.eval) {
                caption.getStyleClass().add("true");
            }
        }
    }
});

若要为文本着色,需要使用 -fx-fill 属性而不是 -fx-text-fill 属性。

最新更新