Search code examples
javajavafxtreeview

Colorize Sub-item, sub-sub-item, sub-sub-sub-item of TreeView


I'm making a program that shows a TreeViews of Strings. When I make a TreeView, is there any way to colorize the strings itens based in the level of the item directly in the CSS?

treeView.getStylesheets().add("style.css");

.tree-cell:sub-tree-item {
    -fx-text-fill: red;
}

.tree-cell:sub-tree-item:sub-tree-item { /*Does exists something similar of this?? */
    -fx-background-color: green ;
}
...

or I have to make Labels

        TreeItem treeNode1 = new TreeItem("");
        Label lteste11=new Label("myLevelIs1");
        lteste11.setTextFill(Color.RED);
        treeNode1.setGraphic(lteste11);

        TreeItem treeNode2 = new TreeItem("");  
        Label lteste22=new Label("myLevelIs2");
        lteste22.setTextFill(Color.GREEN);
        treeNode2.setGraphic(lteste22);
        
        TreeItem treeNodeROOT = new TreeItem(); 
        treeNodeROOT.getChildren().addAll(treeNode1, treeNode2);
        treeView.setRoot(treeNodeROOT);

? Is there other way? enter image description here


Solution

  • You can use a custom cell factory to add style classes based on the depth:

    TreeView<String> tree = ... ;
    
    tree.setCellFactory(tv -> new TreeCell<>() {
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty) ;
            getStyleClass().removeIf(s -> s.startsWith("depth"));
            if (empty || item == null) {
                setText("");
            } else {
                int depth = 0 ;
                for (TreeItem<String> i = getTreeItem().getParent() ; i != null ; i = i.getParent()) {
                    depth++ ;
                }
                getStyleClass().add("depth"+depth);
                setText(item);
            } 
        }
    });
    

    Then in your stylesheet just do, e.g.:

    .tree-cell.depth1 {
        -fx-text-fill: red ;
    }
    .tree-cell.depth2 {
        -fx-background-color: green ;
    }
    

    for as many depths as you want to support.