[an error occurred while processing this directive]
Domain for sale!
Start Search Contents Index Links About
FileTreePanel.java
/*
  
    Copyright (C) 2005  Havard Rast Blok
    http://hblok.sourceforge.net
    
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/


import java.awt.GridLayout;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 * Example which displays the directory structure of the system
 * in a JTree coponent. The nodes are expandable, and will list
 * the sub directories of the selected node.
 
 @author Havard Rast Blok
 *
 */
public class FileTreePanel extends JPanel {

    /** The model which holds the nodes */
    protected TreeModel model;

    /** The tree GUI */
    protected JTree tree;
    
    /** 
     * Constructs the panel which holds a JTree with the file structure.
     */
    public FileTreePanel() {
        //we only need one component
        setLayout(new GridLayout(1,1));
        
        //create the top node 
        MutableTreeNode root = new DefaultMutableTreeNode("Computer");
        
        //get all nodes for top file systems or disks
        //On Linux/Unix this will only be '/'
        //while on Window there will typically be more: 'A:', 'C:' etc. 
        File roots[] = File.listRoots();

        //loop through all these nodes and add them to the root Computer node
        int i = 0;
        for(File f : roots) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(f.getAbsoluteFile().toString());
            root.insert(node, i++);
        }
        
        //create a tree model with the Computer node as root
        model = new DefaultTreeModel(root);
        
        //create a JTree GUI component with the model to display
        tree = new JTree(model);
        
        //add a selection listener, to listen for selected nodes
        tree.addTreeSelectionListener(new MyTreeSelectionListener());
        
        //create scrollbars
        JScrollPane scroll = new JScrollPane(tree);
        
        //and finally add to the panel
        add(scroll);
    }
    
    /**
     * Adds the sub directories, if any, of the given path to the given node.
     
     @param node tree node to add sub directory nodes to 
     @param path file system path to search for sub directories
     */
    protected void addChildren(MutableTreeNode node, String path) {
        //create filter for directories only
        DirectoryFileFilter filter = new DirectoryFileFilter();
        
        //get directories
        File dir = new File(path);
        File subDirs[] = dir.listFiles(filter);
        
        //add sub nodes to given nodes
        if (subDirs != null) {
            int i = 0;
            for (File f : subDirs) {
                MutableTreeNode child = new DefaultMutableTreeNode(f.getName());
                node.insert(child, i++);
            }
        }
    }
    
    /**
     * Inner class which listens for selection events on the tree.
     * When one is received, it will get the path of the selected
     * node and add sub directory nodes, if any, to it.
     */
    class MyTreeSelectionListener implements TreeSelectionListener {

        public void valueChanged(TreeSelectionEvent e) {
            //get the selected tree path
            TreePath path = e.getNewLeadSelectionPath();
            
            //check that a path is in fact selected
            if(path == null) {
                return;
            }
            
            //get the selected node
            DefaultMutableTreeNode curNode = (DefaultMutableTreeNodepath.getLastPathComponent();
            
            //get all the nodes in the selected tree path
            Object nodes[] = path.getPath();
            String dir = "";
            
            //loop through all the tree nodes getting the directory name
            //we start from node one, since node 0, the top node, is the Computer node,
            //which will have no meaning in the file system path
            for (int i = 1; i < nodes.length; i++) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNodenodes[i];
                //the user object will hold the directory name
                dir += (String)node.getUserObject();
                //add the platform independent directory separator character
                dir += File.separator;
            }
            
            //add the sub directory nodes to the selected one
            addChildren(curNode, dir);
            
            //refresh the GUI
            repaint();
        }
        
    }
    
    public static void main(String[] args) {
        //create a JFrame for the example
        JFrame frame = new JFrame();
        
        //exit the application when the frame is closed
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //we need only one component in the frame
        frame.setLayout(new GridLayout(1,1));
        frame.add(new FileTreePanel());
        
        //show the frame
        frame.pack();
        frame.setVisible(true);
    }

}


site: Håvard Rast Blok
mail:
updated: 16 July 2010