簡體   English   中英

按字母順序對JTree節點進行排序

[英]Sort JTree nodes alphabetically

幾天來,我一直在嘗試對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;
}

在這方面的任何幫助都將非常棒。

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

只需對父級的子級列表進行排序並調用模型的方法nodeStructureChanged(parent)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM