【问题标题】:Sort JTree nodes alphabetically按字母顺序对 JTree 节点进行排序
【发布时间】:2015-01-13 11:08:31
【问题描述】:

几天来,我一直在尝试对 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;
}

对此的任何帮助都会非常棒。

【问题讨论】:

    标签: java swing sorting jtree


    【解决方案1】:

    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;
    }
    

    【讨论】:

    • 首先感谢Alex的回复!在我的 jtree 中,我的文件名如下:Name_someNumber_2014.txt,此方法仅对仅包含字母的文件名进行排序,或者它将对名称中同时包含数字和字母的名称进行排序?
    • 你可以尝试使用that问题的比较器。
    【解决方案2】:

    只需对父级的子级列表进行排序并调用模型的方法nodeStructureChanged(parent)。

    【讨论】:

      猜你喜欢
      • 2012-03-31
      • 2011-08-29
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多