Java JTree visit all expanded tree node

Description

Java JTree visit all expanded tree node


import java.util.Enumeration;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class Main {
   public static void main(String[] args) {
      DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
      rootNode.add(a);/*www .  j  a v a 2s  .  com*/

      DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("1");
      a.add(a1);
      DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("2");
      a.add(a2);

      DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
      rootNode.add(b);
      DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("1");
      b.add(b1);

      JTree tree = new JTree(rootNode);

      visitAllExpandedNodes(tree);

      tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

      JFrame f = new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(new JScrollPane(tree));
      f.setSize(250, 250);
      f.setVisible(true);
   }

   public static void visitAllExpandedNodes(JTree tree) {
      TreeNode root = (TreeNode) tree.getModel().getRoot();
      visitAllExpandedNodes(tree, new TreePath(root));
   }

   public static void visitAllExpandedNodes(JTree tree, TreePath parent) {
      // Return if node is not expanded
      if (!tree.isVisible(parent)) {
         return;
      }

      // node is visible and is visited exactly once
      TreeNode node = (TreeNode) parent.getLastPathComponent();
      System.out.println(node);

      if (node.getChildCount() >= 0) {
         for (Enumeration e = node.children(); e.hasMoreElements();) {
            TreeNode n = (TreeNode) e.nextElement();
            TreePath path = parent.pathByAddingChild(n);
            visitAllExpandedNodes(tree, path);
         }
      }
   }
}



PreviousNext

Related