sort JTree Nodes Alphabetically - Java Swing

Java examples for Swing:JTree

Description

sort JTree Nodes Alphabetically

Demo Code

/*******************************************************************************
 * Copyright (c) JavaPEG developers//from w w w .  j  a v a  2  s  .co  m
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.util.*;

public class Main{
    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, new IgnoreCaseComparator());

            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();
        }
    }
}

Related Tutorials