Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

File System Tree Control Implementation

Having seen the basic idea, let's now examime the implementation, the code for which appears in Listing 10–3.

Listing 10–3 A custom control to display a file system in a tree

package JFCBook.Chapter10; 

import javax.swing.*; 
import javax.swing.tree.*; 
import javax.swing.event.*; 
import java.io.*; 
import java.util.*; 

public class FileTree extends JTree {
  public FileTree(String path) 
      throws FileNotFoundException, SecurityException {
  super((TreeModel)null);// Create the JTree itself 

  // Use horizontal and vertical lines
  putClientProperty("JTree.lineStyle", "Angled"); 

  // Create the first node 
  FileTreeNode rootNode = new FileTreeNode(null, path); 

  // Populate the root node with its subdirectories
  boolean addedNodes = rootNode.populateDirectories(true);
  setModel(new DefaultTreeModel(rootNode)); 

  // Listen for Tree Selection Events
  addTreeExpansionListener(new TreeExpansionHandler()); 

// Returns the full pathname for a path, or null
// if not a known path
public String getPathName(TreePath path) {
  Object o = path.getLastPathComponent();
  if (o instanceof FileTreeNode) {
     return ((FileTreeNode)o).file.getAbsolutePath();
  } return null;

// Returns the File for a path, or null if not a known path
public File getFile(TreePath path) { 
  Object o = path.getLastPathComponent();
  if (o instanceof FileTreeNode) {
    return ((FileTreeNode)o).file;
  return null;

// Inner class that represents a node in this
// file system tree
protected static class FileTreeNode
              extends DefaultMutableTreeNode {
  public FileTreeNode(File parent, String name)
      throws SecurityException, FileNotFoundException { 
  this.name = name; 

  // See if this node exists and whether it
  // is a directory
  file = new File(parent, name);
  if (!file.exists()) {
    throw new FileNotFoundException("File " + name + " does not exist");

  isDir = file.isDirectory(); 

  // Hold the File as the user object.


// Override isLeaf to check whether this is a directory 
public boolean isLeaf() {
  return !isDir; 

// Override getAllowsChildren to check whether
// this is a directory
public boolean getAllowsChildren() {
  return isDir;

// For display purposes, we return our own name public String toString() { return name; } 
// If we are a directory, scan our contents and populate
// with children. In addition, populate those children
// if the "descend" flag is true. We only descend once,
// to avoid recursing the whole subtree.
// Returns true if some nodes were added
boolean populateDirectories(boolean descend) {
  boolean addedNodes = false; 
// Do this only once 
if (populated == false) {
  if (interim == true) { 
    // We have had a quick look here before:
    // remove the dummy node that we added last time
    interim = false; 

  String[] names = file.list();// Get list of contents 

  // Process the directories
  for (int i = 0; i < names.length; i++) {
    String name = names[i];  
    File d = new File(file, name);
    try {
      if (d.isDirectory()) {
        FileTreeNode node =
                new FileTreeNode(file, name);
        if (descend) {
        addedNodes = true;
        if (descend == false) {
          // Only add one node if not descending 
          break; }
    } catch (Throwable t) {
      // Ignore phantoms or access problems

  // If we were scanning to get all subdirectories,
  // or if we found no subdirectories, there is no
  // reason to look at this directory again, so
  // set populated to true. Otherwise, we set interim
  // so that we look again in the future if we need to
  if (descend == true || addedNodes == false) {
    populated = true; 
  } else {
  // Just set interim state
          interim = true;
      return addedNodes; 

    protected File file;// File object for this node 
    protected String name;// Name of this node 
    protected boolean populated;
                      // true if we have been populated 
    protected boolean interim;
                      // true if we are in interim state 
    protected boolean isDir;// true if this is a directory

  // Inner class that handles Tree Expansion Events
  protected class TreeExpansionHandler
                    implements TreeExpansionListener {
    public void treeExpanded(TreeExpansionEvent evt) { 
      TreePath path = evt.getPath();// The expanded path JTree tree =
      (JTree)evt.getSource();// The tree 

      // Get the last component of the path and
      // arrange to have it fully populated.
      FileTreeNode node = 
      if (node.populateDirectories(true)) {

    public void treeCollapsed(TreeExpansionEvent evt) {
      // Nothing to do 

Naturally enough, the control, called FileTree, is derived from JTree. It is a self-contained component that is given a directory name as its starting point—that's all you need to do to get a hierarchical display of the objects below that directory. The component can be placed in a JScrollPane and used just like any other tree.

Designing the Data Model

The constructor first invokes the JTree constructor, creating a tree with no data model, then starts building the contents of the control by creating a DefaultTreeModel that initially contains just a node for the starting directory. The obvious question that arises is whether to use a DefaultMutable-TreeNode to represent the directories, or to create a node class of our own.

This turns out to be a pretty simple decision. Suppose we chose to use a DefaultMutableTreeNode. Along with each node, we need to store something that connects it to the object in the file system that it represents. The most natural way to do this is to use the file or directory's File object and store it as the user object of the DefaultMutableTreeNode. However, simply populating the model with DefaultMutableTreeNodes set up in this way would not work, because the tree uses the toString method of a node's user object to obtain the text to be displayed for that node. In this case, we need the tree to display the last component of the file name, which is not what the toString method of File returns. Instead, we create a private node class to represent each object in the part of the file system that the tree will display. Because this class is tied to the design of the tree, it is implemented as an inner class of the tree, called

FileTreeNode and is derived, naturally, from DefaultMutableTreeNode. This class will store the File object and the node's name relative to its parent, both of which will be passed as arguments to the constructor. To achieve the correct display, the toString method will return the latter of these two values. It turns out that we wouldn't actually need to store the File as the node's user object, but we choose to do so anyway so that an application that listens to selection events from the FileTree component can get easy access to the corresponding File.

Building the Initial Data Model

Construction of the data model begins with the node for the initial directory, to which other nodes must be added for each of its immediate subdirectories. This task is delegated to a method of FileTreeNode called populateDi-rectories, which you'll see in a moment. When this method returns, a DefaultTreeModel initialized with the root node is created and the JTree setModel method is used to attach it to the tree. The model as created by this method is sufficient for the initial display of the tree and will remain suf-ficient until the user (or the application) expands one of the nodes. To handle this (likely) eventuality, the last thing the FileTree constructor has to do is register a listener for TreeExpansionEvents. The code that will handle these events is encapsulated in a separate inner class called TreeExpan-sionHandler, to avoid cluttering FileTree with methods that aren't part of its public interface. The constructor for FileTree creates an instance of this class and registers it to receive the events. At this point, the control is fully initialized and ready to be displayed.

Apart from its constructor, FileTree only has two methods of its own. The getPathName method is a convenience method that accepts a TreePath as its argument and returns the path name of the file that it represents in the tree. Similarly, the getFile method accepts a TreePath argument and returns the File object for the file that it represents.

Once the tree model has been created, it is managed entirely by the JTree class. All that remains for us to do is implement the inner classes FileTreeN-ode and TreeExpansionHandler.

Implementing the FileTreeNode Class

The FileTreeNode class is derived from DefaultMutableTreeNode so that it can be added to a tree. Its constructor has two arguments that give the File object for the directory that it resides in and name of the object that it represents relative to that directory. These values are combined to create a File object for the target file or directory, which is stored in both the instance variable file and as the user object of the node. For convenience, the file name passed to the constructor is also stored in the instance variable name, from which it can be quickly retrieved by the toString method. The case of the root node (the one that represents the initial directory) is a special one, because it does not have a parent File object. In this case, the File argument can be supplied as null.

All that remains for the constructor to do is to determine whether the node's associated object in the file system is a directory or not. This is easily done be calling the isDirectory method of the newly constructed File object. The result of this call is stored in an instance variable called isDir, of type boolean. Unfortunately, this method returns false if the object is not a directory or if it doesn't exist. Most of the time, objects will be constructed using names that have been discovered by reading the file system, which (subject to possible race conditions) should exist, but the node at the top of the tree will be built based on information supplied by the user, so it might not exist. To be safe, the existence of the object is verified by using the exists method and a FileNotFoundException is thrown if necessary. On some systems (e.g., UNIX and Windows NT), it may turn out that the user of the control doesn't have access to the directory in which the object resides, or to the object itself. On these systems, the constructor will throw a Securi-tyException. If either of these exceptions occurs while the tree is being built, they are just caught and ignored, with the result that the tree will be properly constructed but won't contain those objects that it couldn't get access to. The exception to this is the root node, which is built in the File-Tree constructor: Any problem creating this is passed as an exception to the code creating the tree.

Core Note

A nice enhancement to this control might be to catch a SecurityException and represent the object that could not be accessed in some meaningful way to the user—perhaps with an icon representing a NO ENTRY sign. You shouldn't find it too difficult, as an exercise, to add this functionality.

FileTreeNode Icon and Text Representation

Before looking in detail at how to handle the population of subdirectories, there is a small point that needs to be dealt with. JTree has a small selection of icons that it can display for any given node—a sheet of paper representing a leaf, a closed folder, and an open folder (in the Metal look-and-feel), both of which are used for branch nodes. As you know, there are two different ways to determine whether a node considers itself to be a leaf, only one of which is usually appropriate for a particular type of node: Either its isLeaf method or its getAllowsChildren method should be called. In the case of a file system, directories are never leaves, even if they are empty, so it would be normal to implement the getAllowsChildren method and have it return false if the node represents a directory and true otherwise. For flexibility, the FileTreeNode class also implements the isLeaf method, which returns the inverse of whatever is returned by getAllowsChildren. Since both of these return correct answers for any node, there is no need to tell the DefaultTreeModel which method to use, so the default setting is used when the data model is created (which means that isLeaf will be called).

The text that is rendered alongside the icon is obtained by invoking the toString method of the object that represents the node—that is, the toString method of FileTreeNode—so, as noted earlier, this method is overridden to return the name of the component.

Populating Directory Nodes

The last important piece of the FileTreeNode class is the populateDi-rectories method, which contains the code to create nodes to represent subdirectories. As noted earlier, sometimes it is necessary to create nodes for all of a directory's subdirectories and sometimes only one node is needed so that the directory's icon shows that it can be expanded. In fact, these actions will always need to be carried out in pairs, one immediately after the other. To see why this is, consider the file system example that is shown above and imagine what needs to happen when the root node for the C:\java directory is created. The first thing to do is to get a list of the directories in the directory C:\java. Since all of these are going to be shown straight away, it is necessary to create nodes for each of them immediately and attach them to the root node. If any of these directories has subdirectories, a single node must be attached to them, to show that the directory is expandable. So, for each directory that is created in populateDirectories, there will need a second scan that creates no more than one node under it. Since both of these operations involve scanning a directory and creating a node (or nodes) to attach to the directory's node, the same code can be used for each case.

For this reason, the populateDirectories method takes a boolean argument called descend. When it is called to populate a directory whose content is going to be displayed because its node is being expanded, this parameter is set to true and the entire directory will be scanned and populated. On the other hand, when it is called to scan a newly-discovered subdirectory which will be displayed as a collapsed node, descend will be set to false. If descend is false, the loop that processes each directory will terminate when it finds a subdirectory. Also, if descend is false, discovering a subdirectory doesn't cause populateDirectories to descend into it—which is the reason for the name. If this were not done, populateDirecto-ries would always recursively descend down to the end of one path on the file system, instead of scanning only two levels.

Let's see how this works in practice. Refer to the implementation of pop-ulateDirectories in Listing 10-3 as you read this. When this method is first called, descend is set to true. Ignore, for a moment, the populated and interim instance variables, which are both initially false—you'll see how these are used in a moment. The first thing to do is create a File object for the node and get a list of its contents using the list method.

Core Note

Notice that this code is very carefully arranged so that, if it gets a SecurityException, it returns having done no damage to the tree structure. This means that the tree will be incomplete, but will reflect those parts of the file system that the user has access to.

In the case of the example file system, this will return the following list of subdirectories:

bin, demo, docs, include, lib, src 

It will also return the names of any files in the java directory; on my machine, there are several of these, but I've left them out of this list for clarity. A FileTreeNode for each of these directories must be added to the node that represents the directory being scanned. This job is carried out by the for loop, which makes one pass for each name in the list. Each time round the loop, it creates a File object for one of the above names (and the files that I haven't shown) and checks whether it represents a directory. If it doesn't, it is ignored and the next pass of the loop is started. In the case of a directory, it creates a FileTreeNode, passing the File object of the parent (which is the File object of the current node) and the component name from the list (i.e., bin or demo, etc.), then adds it underneath the node for the directory that is being scanned. Next comes the interesting part. If descend is true, which is the case when a directory node is being expanded, populateDirectories is called again, but this time there are two important differences:

  • The descend argument changes to false.

  • The node on which it operates is the new node (i.e., that for bin, demoetc.), not the top-level node.

This second call does the same things again for the subdirectory that it is dropping into, but it stops sooner—as soon as any subdirectory is found. This call is made for each of the directories in the original list (i.e., bin, demo, docs, include, lib and src). In the case of bin, there are no subdirectories, so it will complete the for loop without finding anything and just return (what happens to the populated and interim fields will be discussed below). However, the second pass of the loop calls populateDirectories for the demo node, which does have subdirectories. In this case, the list method returns the following set of names (and possibly some files that will be ignored because they have no bearing on how the data model is constructed):

Animator, ArcTest, awt-1.1, BarChart 

Now the for loop is entered and the code starts handling the subdirectory Animator. This turns out to be a directory, so a FileTreeNode is built for it and attached under the node for C:\java\demo. However, this time, descend is false, so populateDirectories is not called again to descend into this new directory. Instead, the for loop ends, having added exactly one child to C:\java\demo. Control now returns to the for loop of the first invocation of populateDirectories, where the rest of the original list of names is processed in the same way but, because here descend is set to true, the loop runs to completion.

When this loop has been completed, the state of the C:\java node needs to be changed to reflect that fact that all of its subdirectories have been located and nodes have been built for them. To indicate this, the populated field is set to true. When populateDirectories is called for a node with populated set to true, it knows that there is nothing more to do and just returns at once. As you'll see, this can happen during tree expansion. On the other hand, the nodes for the subdirectories demo, docs, include, and src have all been processed by populateDirectories and each has had one dummy node added. These directories are not completely processed and it will be necessary to scan them again later if the user expands them in the tree, so it would be incorrect to set populated to true. But it is also necessary to remember that a child has been attached to these nodes so that it can be discarded later before building a fully populated subtree. To distinguish this case, the instance variable interim is set to true, because this node is in an interim state. Note, however, that there is a special case here. If a scan of a subdirectory finds that it has no subdirectories at all, it is marked as populated, because there is nothing to be gained from scanning it again later.

At the end of this process, the following node structure will be as follows:

C:\java (populated) 
   C:\java\bin (populated)
   C:\java\demo (interim)
   C:\java\docs (interim)
   C:\java\include (interim)
   C:\java\lib (populated)
   C:\java\src (interim)

Note that the top-level directory is marked as populated, as are the subdirectories that don't themselves have any further directories (bin and lib). The others are marked as interim, because only one node has been created underneath them and more would need to be added before the user could be allowed to expand, say, C:\java\docs. Notice also that C:\java\include is marked as interim despite the fact that it only has one subdirectory and a node has been created for it. This is because populateDirectories stops after finding one directory, so it wasn't able to see that there weren't any more directories to find. The point of this optimization is the assumption that it is better to stop after finding one directory, on the grounds that if there is one subdirectory there is probably another and, if there isn't, there may still be a large number of files to traverse before getting to the end. Sometimes this guess will be right, other times it won't. In this case, a little more work than is strictly necessary will be done if the user opens this directory, because the node for win32 will be discarded and then put back again.

Handling Expansion of Directories

In terms of the tree as seen by the user, the node structure is now correct and the tree will display the demo, docs, include, and src directories with an expansion icon and the others without one. Nothing will change until the user clicks on one of these icons. Suppose the user clicks on the node for C:\java\demo. Unless something is done, in response to this click the JTree will expand the node and show just the entry for C:\java\demo\Animator. This is, of course, wrong because there are three missing subdirectories. Here is where the TreeExpansionListener comes into play. When the user clicks on the node, the treeExpanded method of the TreeExpansionHan-dler inner class will be entered. The TreeExpansionEvent that it receives tells it the source of the event (i.e., the FileTree instance) and the TreePath for the node that was expanded—for instance a TreePath for C:\java\demo. To give the tree the correct appearance, three new nodes must be added under the node for C:\java\demo, for which it is necessary to find the FileTreeNode for that path.

As you saw earlier in this chapter, given a TreePath, you can find the TreeNode for that path by extracting the path object for the last component in the TreePath. To get the FileTreeNode for C:\java\demo, then, the getLastComponent method is invoked on the TreePath from the event. This returns an Object that is actually the FileTreeNode for the path. Armed with this, the node for C:\java\demo can be populated by invoking populateDirectories against it, passing the argument true to have it process two levels of directory, so that the new directories that get added will get the right expansion icons.

This time, populateDirectories will start at C:\java\demo, which is marked as interim, so it starts by discarding all of its children, which causes the existing node for C:\java\demo\Animator to be removed. Then, it adds nodes for all four subdirectories of C:\java\demo and marks it as populated. Along the way, it will have looked to see if there were directories in any of these four subdirectories and marked the new nodes for the Animator, ArcTest, awt-1.1, and BarChart directories as interim if they were or populated if there were not.

Finally, adding new nodes below an existing node is not sufficient to make the tree show them. To have the tree update its view, the model's node-StructureChanged method must be called, passing it the node for C:\java\demo, since this is the parent node beneath which all of the changes were made. The event handler has a reference to this node, but how is it possible to get hold of a reference to the model? There are two ways to do this. First, the TreeExpansionHandler is a nonstatic inner class of FileTree, which is a JTree, so the model reference can be obtained using the following expression:


This works because FileTree.this refers, by definition, to the containing FileTree. A simpler way, though, is to use the fact that a reference to the JTree is provided as the source of the TreeExpansionEvent, so you can instead just do this:

JTree tree = (JTree)evt.getSource();

This is the approach taken in the implementation.

  • + Share This
  • 🔖 Save To Your Account