Java JTree get all user objects

Description

Java JTree get all user objects

import java.awt.Container;
import java.awt.FlowLayout;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class Main {
   public static void main(String args[]) {
      final JFrame f = new JFrame("JTree Demo");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      c.setLayout(new FlowLayout());
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode c1 = new DefaultMutableTreeNode("X");
      DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("B");
      DefaultMutableTreeNode c3 = new DefaultMutableTreeNode("C");
      root.add(c1);//from w ww  . java  2s .  c o  m
      root.add(c2);
      root.add(c3);

      c1.add(new DefaultMutableTreeNode("1"));
      c1.add(new DefaultMutableTreeNode("2"));

      c2.add(new DefaultMutableTreeNode("3"));
      c2.add(new DefaultMutableTreeNode("4"));

      c3.add(new DefaultMutableTreeNode("5"));
      DefaultMutableTreeNode n6 = new DefaultMutableTreeNode("6");
      n6.setUserObject("demo2s.com");
      c3.add(n6);

      JTree t = new JTree(root);

      Set<Object> set = grepAllUserObjects(t);
      System.out.println(set);

      c.add(new JScrollPane(t));
      f.pack();
      f.setVisible(true);
   }

   public static Set<Object> grepAllUserObjects(JTree tree) {
      Set<Object> rtn = new HashSet<Object>();
      DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree
              .getModel().getRoot();
      grepAllUserObjects(root, rtn);
      return rtn;
  }

  private static <T> void grepAllUserObjects(
          DefaultMutableTreeNode treeNode, Set<Object> set) {
      Object obj = treeNode.getUserObject();
      if (obj != null)
          set.add(obj);
      if (treeNode.getChildCount() == 0)
          return;
      for (int i = 0; i < treeNode.getChildCount(); i++) {
          DefaultMutableTreeNode child = (DefaultMutableTreeNode) treeNode
                  .getChildAt(i);
          grepAllUserObjects(child, set);
      }
  }
}



PreviousNext

Related