import java.awt.Component;
import java.io.File;
import java.util.*;

import javax.swing.*;
import javax.swing.tree.*;


/**
 * @author Remi Forax
 *
 */
public class FileTreeNodeExample {

  static class FileTreeNode implements TreeNode {

    public FileTreeNode(FileTreeNode parent,File file) {
      this.parent=parent;
      this.file=file;
    }
    
    public int getChildCount() {
      return processChildren().size();
    }

    public boolean getAllowsChildren() {
      return true;
    }

    public boolean isLeaf() {
      return !file.isDirectory();
    }

    public Enumeration children() {
      return Collections.enumeration(processChildren());
    }

    public TreeNode getParent() {
      return parent;
    }

    public TreeNode getChildAt(int childIndex) {
      return (FileTreeNode)processChildren().get(childIndex);
    }

    public int getIndex(TreeNode node) {
      return processChildren().indexOf(node);
    }
    
    /*
    public String toString() {
      return file.getName();
    }*/
    
    private List processChildren() {
      if (children!=null)
        return children;
        
      File[] files=file.listFiles();
      ArrayList list=new ArrayList(files.length);
      for(int i=0;i<files.length;i++)
        list.add(new FileTreeNode(this,files[i]));
      this.children=list;
      return list;
    }
    
    private final File file;
    private final FileTreeNode parent;
    private List children;
  }

  public static void main(String[] args) {
    FileTreeNode root=new FileTreeNode(null,new File("/"));
    DefaultTreeModel model=new DefaultTreeModel(root);
    JTree tree=new JTree(model);
    
    tree.setCellRenderer(new DefaultTreeCellRenderer() {
      public Component getTreeCellRendererComponent(
        JTree tree,Object value,boolean selected,
        boolean expanded,boolean leaf,
        int row,boolean hasFocus) {
          
        super.getTreeCellRendererComponent(
          tree,value,selected,expanded,leaf,row,hasFocus);
          
        FileTreeNode node=(FileTreeNode)value;
        setText(node.file.getName());
          
        return this;
      }
    });
    
    JFrame frame=new JFrame("FileTreeNodeExample");
    frame.setContentPane(new JScrollPane(tree));
    frame.pack();
    frame.show();
  }
}
