insert JTree Node In Alphabetical Order - Java Swing

Java examples for Swing:JTree

Description

insert JTree Node In Alphabetical Order

Demo Code

/*******************************************************************************
 * Copyright (c) JavaPEG developers/* ww  w .  ja  v a  2 s . c  om*/
 *
 * 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/>.
 ******************************************************************************/
//package com.java2s;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import java.util.*;

public class Main {
    @SuppressWarnings("unchecked")
    public static void insertNodeInAlphabeticalOrder(
            DefaultMutableTreeNode childNode,
            DefaultMutableTreeNode parentNode, DefaultTreeModel model) {
        Enumeration<DefaultMutableTreeNode> children = parentNode
                .children();

        String nodeName = childNode.toString();
        int index = 0;

        if (children.hasMoreElements()) {
            while (children.hasMoreElements()) {
                String displayString = children.nextElement().toString();
                if (nodeName.compareToIgnoreCase(displayString) < 1) {
                    break;
                }
                index++;
            }
            model.insertNodeInto(childNode, parentNode, index);
        } else {
            model.insertNodeInto(childNode, parentNode, 0);
        }
    }
}

Related Tutorials