Java JTree只扩展一级节点

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

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和下面的级别不是?

5 个解决方案

#1


20  

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

#2


3  

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

你有一些树实用类,它们可以精确地做到:

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.

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

#3


1  

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

#4


0  

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

对所有级别2的节点使用展开(TreePath)。

#5


0  

This should work -

这应该工作

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

#1


20  

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

#2


3  

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

你有一些树实用类,它们可以精确地做到:

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.

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

#3


1  

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

#4


0  

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

对所有级别2的节点使用展开(TreePath)。

#5


0  

This should work -

这应该工作

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