Java Swing How to - Add windows directory structure in JTree








Question

We would like to know how to add windows directory structure in JTree.

Answer

//from   ww  w. jav a  2 s  .  c o m
import java.io.File;

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

public class Main extends JFrame {

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

  private JTree tree;

  public Main() {
    this.tree = new JTree();
    this.add(this.tree);

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

    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);
    
    this.pack();
  }
}