I am trying to implement a search function for a TreeView
in JavaFX. I want to highlight all the matches when the user hits the enter key. So I added a boolean isHighlighted
to my TreeItem
and in my TreeCell
s updateItem
, I check whether the item isHighlighted
and if so I apply a certain CSS. Everything works fine with the items/cells not visible at the moment of the search -- when I scroll to them, they are properly highlighted. The problem is: How can I "repaint" the TreeCells visible at search so that they reflect whether their item isHighlighted
? My Controller does currently not have any reference to the TreeCells
the TreeView
creates.
JavaFX: How to highlight certain Items in a TreeView
2.9k views Asked by spilot At
1
This answer is based on this one, but adapted for
TreeView
instead ofTableView
, and updated to use JavaFX 8 functionality (greatly reducing the amount of code required).One strategy for this is to maintain an
ObservableSet
ofTreeItems
that match the search (this is sometimes useful for other functionality you may want anyway). Use a CSSPseudoClass
and an external CSS file to highlight the required cells. You can create aBooleanBinding
in the cell factory that binds to the cell'streeItemProperty
and theObservableSet
, evaluating totrue
if the set contains the cell's current tree item. Then just register a listener with the binding and update the pseudoclass state of the cell when it changes.Here's a SSCCE. It contains a tree whose items are
Integer
-valued. It will update the search when you type in the search box, matching those whose value is a multiple of the value entered.The CSS file tree-highlight-search.css just has to contain a style for the highlighted cells: