Visiting All the Nodes in a JTree Component - Java Swing

Java examples for Swing:JTree

Description

Visiting All the Nodes in a JTree Component

Demo Code


import java.util.Enumeration;

import javax.swing.JTree;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class Main {
  public void main(String[] argv) {
    JTree tree = new JTree();

    // Add the nodes...

    visitAllNodes(tree);/*w w w.  j  a  va 2 s .c  o  m*/

    visitAllExpandedNodes(tree);
  }

  public void visitAllNodes(JTree tree) {
    TreeNode root = (TreeNode) tree.getModel().getRoot();
    visitAllNodes(root);
  }

  public void visitAllNodes(TreeNode node) {
    //process(node);

    if (node.getChildCount() >= 0) {
      for (Enumeration e = node.children(); e.hasMoreElements();) {
        TreeNode n = (TreeNode) e.nextElement();
        visitAllNodes(n);
      }
    }
  }

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

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

Related Tutorials