简体   繁体   中英

folder sort in jtree

Is there a way to sort an already created tree having only root(DefaultMutableTreeNode)? It has folders and files in random order(With ierarchy). Is it possible to show folders on top of files in alphabetical order?

You can achieve using below recursive method,

public static DefaultMutableTreeNode sortTree(DefaultMutableTreeNode root) {
    {
        for (int i = 0; i < root.getChildCount() - 1; i++) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) root
                    .getChildAt(i);
            String nt = node.getUserObject().toString();

            for (int j = i + 1; j <= root.getChildCount() - 1; j++) {
                DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) root
                        .getChildAt(j);
                String np = prevNode.getUserObject().toString();

                System.out.println(nt + " " + np);
                if (nt.compareToIgnoreCase(np) > 0) {

                    root.insert(node, j);
                    break;
                }
            }
            if (node.getChildCount() > 0) {
                node = sortTree(node);
            }
        }

        return root;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM