设置新的 TreeModel 时如何自动扩展 JTree? [英] How do I auto-expand a JTree when setting a new TreeModel?

查看:10
本文介绍了设置新的 TreeModel 时如何自动扩展 JTree?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的 JTree 和一个自定义的 JModel;当我给它一个新模型时,我希望 JTree 能够自动扩展".目前,它只是将所有节点折叠到根节点.

I have a custom JTree and a custom JModel; I would for the JTree to "auto-expand" when I give it a new model. At the moment, it simply collapse all the nodes to the root.

这是一个例子:

private class CustomTree extends JTree {

    @Override
    public boolean isExpanded(TreePath path) {
        return ((Person) path.getLastPathComponent).hasChildren();

}

private class CustomTreeModel extends TreeModel {

    // ... omitting various implementation details

    @Override
    public boolean isLeaf(Object object) {
        return !((Person) object).hasChildren();
    }

}

Model model = new Model();
Person bob = new Person();
Person alice = new Person();
bob.addChild(alice);
model.setRoot(bob);
JTree tree = new CustomTree(new CustomTreeModel(model));

此时,树正确显示:

- BOB
  - ALICE

其中 Alice 是 Bob 的孩子(在数据和可视化树中)

where Alice is a child of Bob (both in the data and in the visual tree)

但是,如果我打电话:

tree.setModel(new CustomTreeModel(model));

一切都崩溃了:

+ BOB

有没有办法在设置新模型时自动展开"树中的所有内容?

推荐答案

我遇到了类似的问题.

您的解决方案(如https://stackoverflow.com/a/15211697/837530)似乎适用于me 仅用于顶级树节点.

Your solution (as posted https://stackoverflow.com/a/15211697/837530) seemed to work for me only for the top level tree nodes.

但我需要扩展所有的后代节点.所以我用下面的递归方法解决了:

But I needed to expand all the a descendants node. So I solved it with the following recursive method:

private void expandAllNodes(JTree tree, int startingIndex, int rowCount){
    for(int i=startingIndex;i<rowCount;++i){
        tree.expandRow(i);
    }

    if(tree.getRowCount()!=rowCount){
        expandAllNodes(tree, rowCount, tree.getRowCount());
    }
}

被调用

expandAllNodes(tree, 0, tree.getRowCount());

其中,tree 是一个 JTree.

除非有人有更好的解决方案.

Unless someone has a better solution.

这篇关于设置新的 TreeModel 时如何自动扩展 JTree?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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