I am trying to implement onMouseEnter and onMouseExit events on a JavaFX ListView. What I want to do is if the mouse moves over a node of the list view, I want to change the background color of the nodes that are currently visible children in the current view.
This post has a great code sample, but is not quite what I am looking for. Apply style to TreeView children nodes in javaFX
Using that code as a reference, what I am looking for is a given tree:
Root -> Item: 1 -> Item: 100 -> Item 1000, Item 1001, Item 1002, Item 1003
When I mouse over "Item: 100" I would like it and Item 1000* to have a background color change.
This seems difficult to me because the getNextSibling and getPreviousSibling interface is on the TreeItem and though you can get a TreeItem from a TreeCell on the MouseEvent, you can't (that I know of) update CSS on a TreeItem and have it take effect in a TreeCell -- because the setStyle method is on the TreeCell.
Suggestions on how this can be done?
[Update note: I originally had a solution using a subclass of
TreeItem
. The solution presented here is much cleaner than the original.]Create an
ObservableSet<TreeItem<?>>
containing theTreeItem
s that should be highlighted. Then in the cell factory, observe that set, and the cell'streeItemProperty()
, and set the style class (I used aPseudoClass
in the example below) so the cell is highlighted if the tree item belonging to the cell is in the set.Finally, register
mouseEntered
andmouseExited
handlers with the cell. When the mouse enters the cell, you can get the tree item, use it to navigate to any other tree items you need, and add the appropriate items to the set you defined. In themouseExited
handler, clear the set (or perform other logic as needed).highlight-tree-children.css: