Java JTree search by tree path

Description

Java JTree search by tree path


import java.util.Enumeration;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.text.Position.Bias;
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);//ww  w .  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);
      
      TreePath path = find(tree, new String[] {"Root","A"} );
      System.out.println(path);
      
      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 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;
    }

}



PreviousNext

Related