0

我有一个显示一些节点的 BeanTreeView。我还有另一个与 netbeans 无关的组件,此时需要知道树中的内容。最好只是树中节点的直接列表。(澄清;当我在这里谈论节点时,我指的是 netbeans 节点,而不是 JTree 中的 TreeNodes。)

我还没有找到任何有用的方法来做到这一点。我似乎无法从连接到 BeanTreeView 的关联 ExplorerManager 中获取信息。到目前为止,我已经将 BeanTreeView 子类化并添加了私有方法

private List<Object> getNodesAsList(){
    LinkedList<Object> result = new LinkedList<>();
    for (int i = 0; i < tree.getRowCount(); i++) {
        TreePath pathForRow = tree.getPathForRow(i);
        Object lastPathComponent = pathForRow.getLastPathComponent();
        result.add(lastPathComponent);
    }
    return result;
}

我从 getLastPathComponent 得到的 Object 是一个 VisualizerNode,它保存着我想要获取的节点。但我不能转换为 VisualizerNode,因为它在 org.openide.explorer.view 中不公开。这是最终的。无论如何,节点没有吸气剂......

有任何想法吗?我觉得ExplorerManager我错过了一些东西......

更新; 这对我有用,可能会做得更优雅。谢谢稻谷!

private List<Node> getNodesInTree(){
    LinkedList<Node> result = new LinkedList<>();
    ExplorerManager em = ExplorerManager.find(this);
    for (Node node : em.getRootContext().getChildren().getNodes()) {
        result.add(node);
        result.addAll(getChildNodesInTree(node));
    }
    return result;
}

private List<Node> getChildNodesInTree(Node root){
    LinkedList<Node> result = new LinkedList<>();
    if(root.getChildren().getNodesCount() > 0){
        if(isExpanded(root)){
            for (Node node : root.getChildren().getNodes()) {
                result.add(node);
                result.addAll(getChildNodesInTree(node));
            }
        }
    }
    return result;
}
4

1 回答 1

2

你可以使用ExplorerManager.getRootContext(). 这将返回 ExplorerManager 中显示的根节点。从这个节点,您可以遍历所有其他节点(使用Node.getChildren())并创建您自己的列表。我不知道有什么功能可以为您处理。

于 2013-10-09T11:24:02.550 回答