Sort JTree nodes alphabetically

1.1k views Asked by At

I've been trying to sort my nodes in my JTree for a few days now, but with no success. Here is my code to populate the JTree with a structure of a given folder. This is working fine: all the folders are shown in alphabetic order but not the files inside the folders.

DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {

    File[] tmp = dir.listFiles();

    Vector<File> ol = new Vector<File>();
    ol.addAll(Arrays.asList(tmp));

    // Pass two: for files.

    for (int fnum = 0; fnum < ol.size(); fnum++) {

        File file = ol.elementAt(fnum);

        DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);
        if (file.isDirectory()) {
            addNodes(node, file);
        }
        curTop.add(node);
    }

    return curTop;
}

Any help on this would be really great.

2

There are 2 answers

2
alex2410 On BEST ANSWER

dir.listFiles() - doesn't guarantee order of files, because of you need to sort it by yourself like next:

DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {

    File[] tmp = dir.listFiles();
    List<File> ol = new ArrayList<File>(Arrays.asList(tmp));
    Collections.sort(ol, new Comparator<File>() {

        @Override
        public int compare(File o1, File o2) {
            if(o1.isDirectory() && o2.isDirectory()){
                return o1.compareTo(o2);
            } else if(o1.isDirectory()){
                return -1;
            } else if(o2.isDirectory()){
                return 1;
            }
            return o1.compareTo(o2);
        }
    });


    for (int fnum = 0; fnum < ol.size(); fnum++) {

        File file = ol.get(fnum);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);
        if (file.isDirectory()) {
            addNodes(node, file);
        }
        curTop.add(node);
    }

    return curTop;
}
0
Nick Allen On

Just sort the parent's children list and invoke the model's method nodeStructureChanged(parent).