0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ravi Thakur
  • 1
  • 1
  • 1

2 Answers2

1

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);
    }
}
Markus
  • 1,649
  • 1
  • 22
  • 41
0

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?)

user2810910
  • 279
  • 1
  • 2