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

查看:98
本文介绍了在设置新的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 )似乎只适用于顶级树节点。

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

其中, JTree

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

Unless someone has a better solution.

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

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