在设置新TreeModel时如何自动扩展JTree?

时间:2022-04-02 12:32:57

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.

我有一个自定义JTree和一个自定义JModel;当我给它一个新的模型时,我会让JTree“自动扩展”。目前,它只是将所有节点折叠到根目录。

Here is an example:

这是一个例子:

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

At this point, the tree correctly displays:

此时,树正确显示:

- BOB
  - ALICE

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

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

However, if I call:

但是,如果我打电话:

tree.setModel(new CustomTreeModel(model));

everything is collapsed:

一切都崩溃了:

+ BOB

Is there a way to "auto-expand" everything in the tree when setting a new model?

设置新模型时,有没有办法“自动扩展”树中的所有内容?

6 个解决方案

#1


17  

I had a similar problem.

我有类似的问题。

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

您的解决方案(如发布的https://*.com/a/15211697/837530)似乎仅适用于*树节点。

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

which is invoked with

用它调用

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

where, tree is a JTree.

其中,树是JTree。

Unless someone has a better solution.

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

#2


27  

The following worked for me (called after setting the new model):

以下对我有用(在设置新模型后调用):

for (int i = 0; i < tree.getRowCount(); i++) {
    tree.expandRow(i);
}

#3


8  

There's also this non-recursive version.

还有这个非递归版本。

private void expandAllNodes(JTree tree) {
    int j = tree.getRowCount();
    int i = 0;
    while(i < j) {
        tree.expandRow(i);
        i += 1;
        j = tree.getRowCount();
    }
}

#4


1  

this worked for me..

这对我有用..

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Enumeration;

public class JTreeNodeAutoExpandCollapse extends JFrame {
    public JTreeNodeAutoExpandCollapse() throws HeadlessException {
        initializeUI();
    }

    private void initializeUI() {
        setSize(200, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode chapter1 = new DefaultMutableTreeNode("Chapter 1");
        DefaultMutableTreeNode sub1 = new DefaultMutableTreeNode("1.1");
        DefaultMutableTreeNode sub2 = new DefaultMutableTreeNode("1.2");
        DefaultMutableTreeNode sub3 = new DefaultMutableTreeNode("1.3");
        DefaultMutableTreeNode sub31 = new DefaultMutableTreeNode("1.3.1");
        DefaultMutableTreeNode sub32 = new DefaultMutableTreeNode("1.3.2");

        root.add(chapter1);
        chapter1.add(sub1);
        chapter1.add(sub2);
        chapter1.add(sub3);
        sub3.add(sub31);
        sub3.add(sub32);

        final JTree tree = new JTree(root);
        expandTree(tree, false);

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(200, 200));

        JPanel buttonPanel = new JPanel(new BorderLayout());
        JButton expandAll = new JButton("Expand All");
        expandAll.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                expandTree(tree, true);
            }
        });

        JButton collapseAll = new JButton("Collapse All");
        collapseAll.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                expandTree(tree, false);
            }
        });

        buttonPanel.add(expandAll, BorderLayout.WEST);
        buttonPanel.add(collapseAll, BorderLayout.EAST);

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    }

    private void expandTree(JTree tree, boolean expand) {
        TreeNode root = (TreeNode) tree.getModel().getRoot();
        expandAll(tree, new TreePath(root), expand);
    }

    private void expandAll(JTree tree, TreePath path, boolean expand) {
        TreeNode node = (TreeNode) path.getLastPathComponent();

        if (node.getChildCount() >= 0) {
            Enumeration enumeration = node.children();
            while (enumeration.hasMoreElements()) {
                TreeNode n = (TreeNode) enumeration.nextElement();
                TreePath p = path.pathByAddingChild(n);

                expandAll(tree, p, expand);
            }
        }

        if (expand) {
            tree.expandPath(path);
        } else {
            tree.collapsePath(path);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JTreeNodeAutoExpandCollapse().setVisible(true);
            }
        });
    }
}

#5


0  

Since I can neither edit nor comment on the accepted answer to answer the OP's last question:

由于我无法编辑或评论接受OP的最后一个问题的接受答案:

Is there a way to "auto-expand" everything in the tree when setting a new model?

设置新模型时,有没有办法“自动扩展”树中的所有内容?

To expand the tree after a new model is assigned (as requested by the OP), override treeDidChange() in your custom tree:

要在分配新模型后(根据OP的请求)展开树,请覆盖自定义树中的treeDidChange():

@Override 
public void treeDidChange() { 
    super.treeDidChange(); 
    expandAllNodes(this, 0, getRowCount());
} 

#6


-3  

TreeUtils.expandAll(tree, true);

TreeUtils will you get from jidesoft. This is not opensource library, but if you have it, you can simply expand all of treenode.

您将从jidesoft获得TreeUtils。这不是开源库,但如果你有它,你可以简单地扩展所有treenode。

http://www.jidesoft.com/javadoc/com/jidesoft/tree/TreeUtils.html

http://www.jidesoft.com/javadoc/com/jidesoft/tree/TreeUtils.html

#1


17  

I had a similar problem.

我有类似的问题。

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

您的解决方案(如发布的https://*.com/a/15211697/837530)似乎仅适用于*树节点。

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

which is invoked with

用它调用

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

where, tree is a JTree.

其中,树是JTree。

Unless someone has a better solution.

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

#2


27  

The following worked for me (called after setting the new model):

以下对我有用(在设置新模型后调用):

for (int i = 0; i < tree.getRowCount(); i++) {
    tree.expandRow(i);
}

#3


8  

There's also this non-recursive version.

还有这个非递归版本。

private void expandAllNodes(JTree tree) {
    int j = tree.getRowCount();
    int i = 0;
    while(i < j) {
        tree.expandRow(i);
        i += 1;
        j = tree.getRowCount();
    }
}

#4


1  

this worked for me..

这对我有用..

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Enumeration;

public class JTreeNodeAutoExpandCollapse extends JFrame {
    public JTreeNodeAutoExpandCollapse() throws HeadlessException {
        initializeUI();
    }

    private void initializeUI() {
        setSize(200, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode chapter1 = new DefaultMutableTreeNode("Chapter 1");
        DefaultMutableTreeNode sub1 = new DefaultMutableTreeNode("1.1");
        DefaultMutableTreeNode sub2 = new DefaultMutableTreeNode("1.2");
        DefaultMutableTreeNode sub3 = new DefaultMutableTreeNode("1.3");
        DefaultMutableTreeNode sub31 = new DefaultMutableTreeNode("1.3.1");
        DefaultMutableTreeNode sub32 = new DefaultMutableTreeNode("1.3.2");

        root.add(chapter1);
        chapter1.add(sub1);
        chapter1.add(sub2);
        chapter1.add(sub3);
        sub3.add(sub31);
        sub3.add(sub32);

        final JTree tree = new JTree(root);
        expandTree(tree, false);

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(200, 200));

        JPanel buttonPanel = new JPanel(new BorderLayout());
        JButton expandAll = new JButton("Expand All");
        expandAll.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                expandTree(tree, true);
            }
        });

        JButton collapseAll = new JButton("Collapse All");
        collapseAll.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                expandTree(tree, false);
            }
        });

        buttonPanel.add(expandAll, BorderLayout.WEST);
        buttonPanel.add(collapseAll, BorderLayout.EAST);

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    }

    private void expandTree(JTree tree, boolean expand) {
        TreeNode root = (TreeNode) tree.getModel().getRoot();
        expandAll(tree, new TreePath(root), expand);
    }

    private void expandAll(JTree tree, TreePath path, boolean expand) {
        TreeNode node = (TreeNode) path.getLastPathComponent();

        if (node.getChildCount() >= 0) {
            Enumeration enumeration = node.children();
            while (enumeration.hasMoreElements()) {
                TreeNode n = (TreeNode) enumeration.nextElement();
                TreePath p = path.pathByAddingChild(n);

                expandAll(tree, p, expand);
            }
        }

        if (expand) {
            tree.expandPath(path);
        } else {
            tree.collapsePath(path);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JTreeNodeAutoExpandCollapse().setVisible(true);
            }
        });
    }
}

#5


0  

Since I can neither edit nor comment on the accepted answer to answer the OP's last question:

由于我无法编辑或评论接受OP的最后一个问题的接受答案:

Is there a way to "auto-expand" everything in the tree when setting a new model?

设置新模型时,有没有办法“自动扩展”树中的所有内容?

To expand the tree after a new model is assigned (as requested by the OP), override treeDidChange() in your custom tree:

要在分配新模型后(根据OP的请求)展开树,请覆盖自定义树中的treeDidChange():

@Override 
public void treeDidChange() { 
    super.treeDidChange(); 
    expandAllNodes(this, 0, getRowCount());
} 

#6


-3  

TreeUtils.expandAll(tree, true);

TreeUtils will you get from jidesoft. This is not opensource library, but if you have it, you can simply expand all of treenode.

您将从jidesoft获得TreeUtils。这不是开源库,但如果你有它,你可以简单地扩展所有treenode。

http://www.jidesoft.com/javadoc/com/jidesoft/tree/TreeUtils.html

http://www.jidesoft.com/javadoc/com/jidesoft/tree/TreeUtils.html