// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

import com.sun.java.swing.*;       // Beta package name; will change
import com.sun.java.swing.border.*;
import java.awt.*;
import java.io.*;

/**
 * This class displays a JTree object within a JScrollPane object.
 **/
public class TreePanel extends JBorderedPane {
  public TreePanel(String directory) {
    // Set the title for the pane
    this.setBorder(new JTitledBorder(this, "Tree"));
    
    // To display a tree, we need to give it a data structure that contains
    // data organized in a hierarchy.  The TreeNode object allows us to do
    // this.  Here, we go get a TreeNode that represents the specified
    // directory and all of its files and subdirectories.
    TreeNode root = maketree(new File(directory));

    // When we create a tree, we must specify the TreeModel which contains
    // the hierarchial data it will display.  The JFC uses the Model-View-
    // Controller paradigm.  According to this paradigm, the JTree object 
    // provides a view of the tree data (the "model").  The JTreeModel class
    // is a class that implements TreeModel using the tree represented by a
    // TreeNode object.
    JTree tree = new JTree(new JTreeModel(root));

    // A tree display can become quite large, so the JTree object should
    // usually appear within a JScrollPane to allow it to scroll.
    JScrollPane scroll = new JScrollPane();
    scroll.getViewport().add(tree);

    // Set a layout manager for this pane, and add the JScrollPane 
    // (which contains the JTree) to it.
    this.setLayout(new BorderLayout());
    this.add(scroll, "Center");
  }

  /**
   * This method recursively creates a hierarchy of TreeNode objects that
   * represent the files and subdirectories of a given directory.
   **/
  TreeNode maketree(File f) {
    TreeNode t = new TreeNode(f.getName());
    if (f.isDirectory()) {
      String[] list = f.list();
      for(int i = 0; i < list.length; i++) 
        t.add(maketree(new File(f, list[i])));
    }
    return t;
  }
}
