Java JTree Node sortTreeNode(DefaultMutableTreeNode root)

Here you can find the source of sortTreeNode(DefaultMutableTreeNode root)

Description

sort Tree Node

License

Apache License

Declaration

public static DefaultMutableTreeNode sortTreeNode(DefaultMutableTreeNode root) 

Method Source Code

//package com.java2s;
/*// w  w  w .j a  v a2 s. com
 * K-scope
 * Copyright 2012-2013 RIKEN, Japan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Version to work with SSHconnect.
 */

import javax.swing.tree.DefaultMutableTreeNode;

public class Main {

    public static DefaultMutableTreeNode sortTreeNode(DefaultMutableTreeNode root) {
        if (root == null)
            return root;
        int count = root.getChildCount();
        if (count <= 0)
            return root;
        for (int i = 0; i < count; i++) {
            for (int j = count - 1; j > i; j--) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(j);
                String nt = node.getUserObject().toString();
                DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) root.getChildAt(j - 1);
                String np = prevNode.getUserObject().toString();
                if (nt.compareToIgnoreCase(np) < 0) {
                    root.insert(node, j - 1);
                    root.insert(prevNode, j);
                }
            }
            sortTreeNode((DefaultMutableTreeNode) root.getChildAt(i));
        }

        for (int i = 0; i < count; i++) {
            for (int j = count - 1; j > i; j--) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(j);
                DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) root.getChildAt(j - 1);
                if (prevNode.isLeaf() && !node.isLeaf()) {
                    root.insert(node, j - 1);
                    root.insert(prevNode, j);
                }
            }
        }

        return root;
    }
}

Related

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