Customize the properties of a TreeCell
by overriding the updateItem
method, allowing you to adjust its appearance based on the value of the TreeItem
it contains.
In this example, cells containing values with the prefix "child"
are assigned a pseudoclass, while empty cells receive a black background.
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) {
// Customize for empty or null-filled cell
pseudoClassStateChanged(childPseudoClass, false);
setText("");
setStyle("-fx-background-color: black;");
} else {
// Customize for filled cell
pseudoClassStateChanged(childPseudoClass, item.startsWith("child"));
setText(item);
setStyle(null);
}
}
});
CSS Stylesheet
.tree-cell:child {
-fx-background-color: red;
}
The updateItem
method is triggered by the TreeView
whenever the value changes, such as when a new TreeItem
is linked to the cell or the value
property of a TreeItem
is altered.
You can also use the factory to attach listeners to the TreeCell
, before it's returned, if you prefer this approach and wish to modify the cell based on the treeItem
property.
EDIT: Different colors for text require using separate Node
s for each text section.
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");
}
}
}
});
To color the text, utilize the -fx-fill
property rather than the -fx-text-fill
property.