Java JTree 只扩展一级节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/510610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:34:04  来源:igfitidea点击:

Java JTree expand only level one nodes

javaswingjtree

提问by garyLynch

With a JTree, assuming the root node is level 0 and there may be up to 5 levels below the root, how can I easily expand all the level 1 nodes so that all level 1 & 2 branches and leafs are visible but levels 3 and below aren't?

使用 JTree,假设根节点为 0 级并且根以下最多可能有 5 个级别,我如何轻松扩展所有 1 级节点,以便所有 1 级和 2 级分支和叶子都可见,但级别 3 及以下不是吗?

采纳答案by garyLynch

Thanks for the quick response guys. However I have now found the simple solution I was looking for. For some reason I just couldn't see DefaultMutableTreeNode.getLevel() in the JavaDocs! FYI what I'm doing now is:

感谢您的快速反应家伙。但是,我现在找到了我正在寻找的简单解决方案。出于某种原因,我在 JavaDocs 中看不到 DefaultMutableTreeNode.getLevel() !仅供参考,我现在正在做的是:

DefaultMutableTreeNode currentNode = treeTop.getNextNode();
do {
    if (currentNode.getLevel() == 1) 
        myTree.expandPath(new TreePath(currentNode.getPath()));
    currentNode = currentNode.getNextNode();
} while (currentNode != null);

回答by Bombe

Use expand(TreePath)for all level-2 nodes.

对所有 2 级节点使用expand(TreePath)

回答by VonC

You have some Tree utility classes out there which do precisely that:

您有一些 Tree 实用程序类,它们正是这样做的:

Like this one:

这个

public class SimpleNavigatorTreeUtil {

   /**
    * Expands/Collapse specified tree to a certain level.
    * 
    * @param tree jtree to expand to a certain level
    * @param level the level of expansion
    */
   public static void expandOrCollapsToLevel(JTree tree, TreePath treePath,int level,boolean expand) {
      try {
         expandOrCollapsePath(tree,treePath,level,0,expand);
      }catch(Exception e) {
e.printStackTrace();
         //do nothing
      }
   }

   public static void expandOrCollapsePath (JTree tree,TreePath treePath,int level,int currentLevel,boolean expand) {
//      System.err.println("Exp level "+currentLevel+", exp="+expand);
      if (expand && level<=currentLevel && level>0) return;

      TreeNode treeNode = ( TreeNode ) treePath.getLastPathComponent();
      TreeModel treeModel=tree.getModel();
      if ( treeModel.getChildCount(treeNode) >= 0 ) {
         for ( int i = 0; i < treeModel.getChildCount(treeNode); i++  ) {
            TreeNode n = ( TreeNode )treeModel.getChild(treeNode, i);
            TreePath path = treePath.pathByAddingChild( n );
            expandOrCollapsePath(tree,path,level,currentLevel+1,expand);
         }
         if (!expand && currentLevel<level) return;
      }      
      if (expand) {
         tree.expandPath( treePath );
//         System.err.println("Path expanded at level "+currentLevel+"-"+treePath);
      } else {
         tree.collapsePath(treePath);
//         System.err.println("Path collapsed at level "+currentLevel+"-"+treePath);
      }
   }


}


Basically, you need to explore the sub-nodes until your criteria (here the depth level) is met, and expand all nodes until that point.

基本上,您需要探索子节点,直到满足您的标准(此处为深度级别),然后展开所有节点直到该点。

回答by garyLynch

The following works for first level children. To expand ALL children replace .children() with .breadthFirstEnumeration()

以下适用于一级儿童。要扩展所有子项,将 .children() 替换为 .breadthFirstEnumeration()

import javax.swing.*;
import javax.swing.tree.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.util.*;

public class Tree {
    public static void main(String[] args) {
        JPanel panel = new JPanel(new BorderLayout());
        final JTree tree = new JTree();
        panel.add(new JScrollPane(tree));
        JButton btn = new JButton("Press Me");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                for (Enumeration e = ((TreeNode)tree.getModel().getRoot()).children();e.hasMoreElements();) {
                    TreeNode tn = (TreeNode)e.nextElement();
                    tree.expandPath(new TreePath(((DefaultTreeModel)tree.getModel()).getPathToRoot(tn)));
                }
            }
        });
        panel.add(btn, BorderLayout.SOUTH);
        JFrame frame = new JFrame("");
        frame.getContentPane().add(panel);
        frame.setSize(300, 300);
        frame.setLocation(100, 100);
        frame.pack();
        frame.show();
    }
}

回答by Injektilo

As your level 1 nodes are all children of the root node, and assuming that you are using DefaultMutableTreeNode(needed for the call to getPath()), you can just iterate over the root node's children like so:

由于您的 1 级节点都是根节点的所有子节点,并且假设您正在使用DefaultMutableTreeNode(需要调用getPath()),您可以像这样迭代根节点的子节点:

Enumeration<?> topLevelNodes
    = ((TreeNode)tree.getModel().getRoot()).children();
while(topLevelNodes.hasMoreElements()) {
    DefaultMutableTreeNode node
        = (DefaultMutableTreeNode)topLevelNodes.nextElement();
    tree.expandPath(new TreePath(node.getPath()));
}