Java 按字母顺序对JTree节点排序

Java 按字母顺序对JTree节点排序,java,swing,sorting,jtree,Java,Swing,Sorting,Jtree,几天来,我一直在尝试对JTree中的节点进行排序,但没有成功。 下面是我用给定文件夹的结构填充JTree的代码。这很好:所有文件夹都按字母顺序显示,但文件夹中的文件不显示 DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) { File[] tmp = dir.listFiles(); Vector<File> ol = new Vector<File>();

几天来,我一直在尝试对JTree中的节点进行排序,但没有成功。 下面是我用给定文件夹的结构填充JTree的代码。这很好:所有文件夹都按字母顺序显示,但文件夹中的文件不显示

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;
}
DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop,文件目录){
File[]tmp=dir.listFiles();
向量ol=新向量();
ol.addAll(Arrays.asList(tmp));
//通过二:文件。
对于(int-fnum=0;fnum
这方面的任何帮助都将非常有用。

dir.listFiles()
-不能保证文件的顺序,因为您需要像下面这样自己排序:

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;
}
DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop,文件目录){
File[]tmp=dir.listFiles();
List ol=newarraylist(Arrays.asList(tmp));
Collections.sort(ol,新的Comparator(){
@凌驾
公共整数比较(文件o1、文件o2){
if(o1.isDirectory()&&o2.isDirectory()){
返回o1。与(o2)相比;
}else if(o1.isDirectory()){
返回-1;
}else if(o2.isDirectory()){
返回1;
}
返回o1。与(o2)相比;
}
});
对于(int-fnum=0;fnum
只需对父项的子项列表进行排序,并调用模型的方法
节点结构更改(父项)

首先,感谢您的回复!在我的jtree中,我有一些文件名,比如:Name_someNumber_2014.txt,这种方法只对文件名进行字母排序,或者对名称中的数字和字母进行排序?您可以尝试使用问题中的comparator。