My solution to this is to use weak references:
[A] weak reference is a reference that does not protect the referenced object from collection by a garbage collector[.]
So, add this to your controller:
private final Set<MyTreeCell> myTreeCells = Collections.newSetFromMap(new WeakHashMap<>());
And make your CellFactory look like this:
myTreeView.setCellFactory((treeItem) -> {
MyTreeCell c = new MyTreeCell(icf);
Platform.runLater(() -> myTreeCells.add(c));
return c;
});
Now, myTreeCells
will always contain the currently existing TreeCells.
Update
There is another, quite ugly solution using reflection to get a List of TreeCells. Note that this List is – as far as I know – a snapshot of JavaFXs List of TreeCells at one point in time. It is not backed.
@SuppressWarnings({ "unchecked" })
private Set<MyTreeCell> getListOfTreeCells() {
try {
final Field f = VirtualContainerBase.class.getDeclaredField("flow");
f.setAccessible(true);
final Field g = VirtualFlow.class.getDeclaredField("cells");
g.setAccessible(true);
final Set<MyTreeCell> s = new HashSet<>();
s.addAll((ArrayLinkedList<MyTreeCell>) g
.get((f.get((myTreeView.skinProperty().get())))));
return s;
}
catch (NoSuchFieldException | SecurityException | IllegalArgumentException
| IllegalAccessException e) {
e.printStackTrace();
}
return null;
}