0

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.

grg
  • 5,023
  • 3
  • 34
  • 50

2 Answers2

0

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;
}
alex2410
  • 10,904
  • 3
  • 25
  • 41
  • First of all, thank you for the response Alex! In my jtree i have file names like: Name_someNumber_2014.txt, this method sort only file names with only letter or it will sort names with both number and letters in the name? – Gabor Beke Nov 17 '14 at 09:36
  • You can try to use comparator from [that](http://stackoverflow.com/questions/16898029/how-to-sort-file-names-in-ascending-order) question. – alex2410 Nov 17 '14 at 09:42
0

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

grg
  • 5,023
  • 3
  • 34
  • 50
Nick Allen
  • 1,647
  • 14
  • 20