Java JTree Node sortTreeNodesAlphaNumeric(final DefaultMutableTreeNode node)

Here you can find the source of sortTreeNodesAlphaNumeric(final DefaultMutableTreeNode node)

Description

not tail recursive!

License

Apache License

Parameter

Parameter Description
node must not be null

Return

the node with sorted children

Declaration

public static DefaultMutableTreeNode sortTreeNodesAlphaNumeric(final DefaultMutableTreeNode node) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;
import java.util.Collections;

import java.util.HashMap;
import java.util.List;

import javax.swing.tree.DefaultMutableTreeNode;

public class Main {
    /**//from   w  ww  .  j  a v a 2s .  c om
     * not tail recursive!
     * 
     * @param node
     *            must not be null
     * @return the node with sorted children
     */
    public static DefaultMutableTreeNode sortTreeNodesAlphaNumeric(final DefaultMutableTreeNode node) {
        List<String> keys = new ArrayList<String>(node.getChildCount());
        HashMap<String, DefaultMutableTreeNode> childMap = new HashMap<String, DefaultMutableTreeNode>(
                node.getChildCount());

        for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
            String key = child.getUserObject().toString();
            keys.add(key);
            childMap.put(key, child);

            sortTreeNodesAlphaNumeric(child);
        }

        Collections.sort(keys);

        node.removeAllChildren();
        for (String key : keys) {
            node.add(childMap.get(key));
        }

        // put folders first
        // for (int i = 0; i < node.getChildCount() - 1; i++) {
        // DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
        // for (int j = i + 1; j <= node.getChildCount() - 1; j++) {
        // DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) node.getChildAt(j);
        //
        // if (!prevNode.isLeaf() && child.isLeaf()) {
        // node.insert(child, j);
        // node.insert(prevNode, i);
        // }
        // }
        // }

        return node;
    }
}

Related

  1. setTreeSelectedNode(JTree tree, TreeNode node)
  2. sort(DefaultMutableTreeNode node)
  3. sortNode(DefaultMutableTreeNode parent, Comparator comparator)
  4. sortTreeDepthFirst(DefaultMutableTreeNode root, Comparator comparator)
  5. sortTreeNode(DefaultMutableTreeNode root)
  6. toArray(final TreeNode node)
  7. treeNodeTest(DefaultMutableTreeNode n)
  8. treetoString(final DefaultMutableTreeNode tree, final String indent)
  9. updateAllVisibleNodes(final JTree tree)