Finding a Node in a JTree Component - Java Swing

Java examples for Swing:JTree

Description

Finding a Node in a JTree Component

Demo Code

import java.util.Enumeration;

import javax.swing.JTree;
import javax.swing.text.Position.Bias;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

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

    int startRow = 0;
    String prefix = "b";
    TreePath path = tree.getNextMatch(prefix, startRow, Bias.Backward);

    startRow = tree.getRowCount() - 1;/*from  w  w  w  .  j  a v a2  s .co  m*/
    prefix = "b";
    path = tree.getNextMatch(prefix, startRow, Bias.Backward);

    path = findByName(tree, new String[] { "JTree", "food", "bananas" });
  }

  public static TreePath find(JTree tree, String[] nodes) {
    TreeNode root = (TreeNode) tree.getModel().getRoot();
    return find2(tree, new TreePath(root), nodes, 0, false);
  }

  public static TreePath findByName(JTree tree, String[] names) {
    TreeNode root = (TreeNode) tree.getModel().getRoot();
    return find2(tree, new TreePath(root), names, 0, true);
  }

  private static TreePath find2(JTree tree, TreePath parent, Object[] nodes,
      int depth, boolean byName) {
    TreeNode node = (TreeNode) parent.getLastPathComponent();
    Object o = node;

    // If by name, convert node to a string
    if (byName) {
      o = o.toString();
    }

    // If equal, go down the branch
    if (o.equals(nodes[depth])) {
      // If at end, return match
      if (depth == nodes.length - 1) {
        return parent;
      }

      // Traverse children
      if (node.getChildCount() >= 0) {
        for (Enumeration e = node.children(); e.hasMoreElements();) {
          TreeNode n = (TreeNode) e.nextElement();
          TreePath path = parent.pathByAddingChild(n);
          TreePath result = find2(tree, path, nodes, depth + 1, byName);
          // Found a match
          if (result != null) {
            return result;
          }
        }
      }
    }

    // No match at this branch
    return null;
  }

}

Related Tutorials