Java JTree sort tree node

Description

Java JTree sort tree node

import java.awt.Container;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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 ww  w  .ja v  a 2s .  co 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");

      c3.add(n6);

      JTree t = new JTree(root);

      sortNodesAlphabetically( root, (DefaultTreeModel)t.getModel());

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

   public static void sortNodesAlphabetically(
         DefaultMutableTreeNode nodeToSort, DefaultTreeModel model) {
     int nrOfChildren = nodeToSort.getChildCount();

     if (nrOfChildren > 1) {
         Map<String, DefaultMutableTreeNode> nameNodeMap = new HashMap<String, DefaultMutableTreeNode>(
                 nrOfChildren);

         for (int i = 0; i < nrOfChildren; i++) {
             DefaultMutableTreeNode child = (DefaultMutableTreeNode) nodeToSort
                     .getChildAt(i);
             nameNodeMap.put(child.toString(), child);
         }

         List<String> names = new ArrayList<String>(nameNodeMap.keySet());

         Collections.sort(names);

         for (DefaultMutableTreeNode node : nameNodeMap.values()) {
             model.removeNodeFromParent(node);
         }

         for (int i = 0; i < names.size(); i++) {
             model.insertNodeInto(nameNodeMap.get(names.get(i)),
                     nodeToSort, i);
         }
         model.reload();
     }
 }
}



PreviousNext

Related