简体   繁体   中英

How to add windows directory structure in JTree?

I am developing an explorer application. In that I want to add a windows directory structure in JTree . Can anybody help me to do that?

you simply need to get the whole filesystem listed. For example choose a root directory (in my case I chose C:/test . With the method listFiles() you get all the items the root file contains (be sure root is a directory!). Then you iterate over this File-Array and add every item to the model.

In your case you need to check every sub-item whether its a directory or a file. If its a directory you just start again and list all sub-items. Read about recursion to implement that.

Here is my code:

/**
 * 
 */
package tests.fileview;

import java.io.File;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

/**
 * FileViewTest created on 02.10.2013<br>
 * <br>
 * Specification:<br>
 */
public class FileViewTest extends JFrame {

    public static void main(String[] args) {
        new FileViewTest().setVisible(true);
    }

    private JTree tree;

    /**
     * 
     */
    public FileViewTest() {
        this.initialize();
        this.build();
        this.configure();
    }

    /**
     *
     */
    public void initialize() {
        this.tree = new JTree();
    }

    /**
     *
     */
    public void build() {
        this.add(this.tree);
    }

    /**
     *
     */
    public void configure() {

        File fileRoot = new File("C:/test");

        DefaultMutableTreeNode root = new DefaultMutableTreeNode(fileRoot);
        DefaultTreeModel model = new DefaultTreeModel(root);

        File[] subItems = fileRoot.listFiles();
        for (File file : subItems) {
            root.add(new DefaultMutableTreeNode(file));
        }

        this.tree.setModel(model);
    }
}

I Googled 'How to add windows directory structure in JTree?' and found several complete examples such as ' http://www.java2s.com/Code/Java/File-Input-Output/DisplayafilesysteminaJTreeview.htm ' (Ain't Google awesome?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM