Java JTree expand only level one nodes
Asked Answered
H

5

12

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?

Handkerchief answered 4/2, 2009 at 9:10 Comment(0)
H
21

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:

DefaultMutableTreeNode currentNode = treeTop.getNextNode();
do {
    if (currentNode.getLevel() == 1) 
        myTree.expandPath(new TreePath(currentNode.getPath()));
    currentNode = currentNode.getNextNode();
} while (currentNode != null);
Handkerchief answered 4/2, 2009 at 9:46 Comment(1)
That is a good solution too: +1. You can accept your own solution if you want (and put it at the top of the answers), but know that you will not gain any rep point.Moina
M
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.

Moina answered 4/2, 2009 at 9:38 Comment(0)
C
1

The following works for first level children. To expand ALL children replace .children() with .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();
    }
}
Cristincristina answered 4/2, 2009 at 9:54 Comment(1)
WARNING! children() get you only one level of children. You need breadthFirstEnumeration(). Then it works.Burse
F
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:

Enumeration<?> topLevelNodes
    = ((TreeNode)tree.getModel().getRoot()).children();
while(topLevelNodes.hasMoreElements()) {
    DefaultMutableTreeNode node
        = (DefaultMutableTreeNode)topLevelNodes.nextElement();
    tree.expandPath(new TreePath(node.getPath()));
}
Furnace answered 2/7, 2012 at 10:5 Comment(0)
H
0

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

Humor answered 4/2, 2009 at 9:19 Comment(2)
yes obviously, but how would I iterate through all the nodes knowing which ones are level 2?Handkerchief
You can do it the way you’ve already done it but you should already have the information in your data model.Humor

© 2022 - 2024 — McMap. All rights reserved.