获取TreeView中当前存在的所有TreeCell对象的列表 [英] Get a list of all TreeCell objects that currently exist in a TreeView

查看:111
本文介绍了获取TreeView中当前存在的所有TreeCell对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道TreeCell对象是TreeView使用单元工厂动态生成的.

I know that TreeCell objects are generated dynamically by the TreeView using a cell factory.

是否可以获取当前存在的所有TreeCell对象的列表?

Is there a way to get a list of all TreeCell objects that currently exist?

我想我可以通过修改单元工厂来跟踪它们.与之类似,每当我创建一个新单元格时,请将其添加到某些列表中.但是然后,我不确定在TreeView放置它们后如何从列表中删除它们(因为它们不在视野之内).

I suppose I could keep track of them by modifying the cell factory. As in, whenever I create a new cell add it to some list. But then I'm not sure how to remove cells from my list once the TreeView disposes them (because they went out of view).

推荐答案

我对此的解决方案是使用弱引用:

My solution to this is to use weak references:

[A]弱引用是一种引用,它不能保护所引用的对象免受垃圾收集器[.]

[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<>());

并使您的CellFactory看起来像这样:

And make your CellFactory look like this:

myTreeView.setCellFactory((treeItem) -> {
        MyTreeCell c = new MyTreeCell(icf);
        Platform.runLater(() -> myTreeCells.add(c));
        return c;
    });

现在,myTreeCells将始终包含当前存在的TreeCell.

Now, myTreeCells will always contain the currently existing TreeCells.

还有另一个非常丑陋的解决方案,它使用反射来获取TreeCells列表.请注意,据我所知,该列表是某个时刻的JavaFXs TreeCells列表的快照.它不支持.

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;
}

这篇关于获取TreeView中当前存在的所有TreeCell对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆