KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > webman > wminstaller > tools > FileTree


1 package de.webman.wminstaller.tools;
2
3 import javax.swing.*;
4 import javax.swing.tree.*;
5 import javax.swing.event.*;
6 import java.io.*;
7 import java.util.*;
8
9 /**
10  * Efficient directory chooser, rereading dir structure at each expansion
11  *
12  * @author <a HREF="mailto:ulf@webman.de">Ulf Goldammer</a>
13  * @version $Revision: 1.2 $
14  **/

15 public class FileTree extends JTree {
16     /* $Id: FileTree.java,v 1.2 2002/02/11 18:26:55 gregor Exp $ */
17
18     String JavaDoc selectedPath = null;
19     /**
20      * Constructor for the FileTree object
21      *
22      *@param path Description of Parameter
23      */

24     public FileTree( TreeSelectionListener tsl) {
25     
26         super( ( TreeModel) null); // Create the JTree itself
27

28         // TODO: icon selection should be coupled with FileTreeElementFilter !!
29
TreeCellRenderer cr = getCellRenderer();
30         if ( cr instanceof DefaultTreeCellRenderer) {
31             DefaultTreeCellRenderer dcr = ( DefaultTreeCellRenderer) cr;
32             dcr.setLeafIcon( dcr.getClosedIcon());
33         }
34         
35         // Use horizontal and vertical lines
36
putClientProperty("JTree.lineStyle", "Angled");
37
38         FileTreeNode diskNode = new FileTreeNode( null, "");
39         diskNode.populateDirectories(); // open up ROOT
40
setModel(new DefaultTreeModel( diskNode));
41         // Listen for Tree Selection Events
42
addTreeExpansionListener( new TreeExpansionHandler());
43         if ( tsl == null) tsl = new TreeSelectionHandler();
44         addTreeSelectionListener( tsl);
45         expandRow( 0);
46     }
47
48     /**
49      * Returns the full pathname for a path, or "" if not a known path
50      *
51      *@param path Description of Parameter
52      *@return The pathName value
53      */

54     public String JavaDoc getPathName( TreePath path) {
55     
56         Object JavaDoc o = path.getLastPathComponent();
57         if ( o instanceof FileTreeNode) { return ( ( FileTreeNode) o).fullName; }
58         return "";
59     }
60
61     public boolean redisplayChildren( TreePath path) {
62         Object JavaDoc obj = path.getLastPathComponent();
63         if ( ! (obj instanceof FileTreeNode)) return false;
64         FileTreeNode node = ( FileTreeNode) obj;
65         node.removeAllChildren();
66         node.hasVisibleSubElements = node.checkVisibleSubElements();
67         node.populateDirectories();
68         ( ( DefaultTreeModel) getModel()).nodeStructureChanged(node);
69         expandPath( path);
70         return true;
71     }
72
73     public boolean redisplayChildren( TreePath path, String JavaDoc selDirName) {
74
75         setEnabled( false);
76         if (! redisplayChildren( path)) {
77             setEnabled( true);
78             return false;
79         }
80         Enumeration e = ( (FileTreeNode) path.getLastPathComponent()).children();
81         String JavaDoc find = getPathName( path) + File.separator + selDirName;
82         FileTreeNode child;
83         while ( e.hasMoreElements()) {
84             child = (FileTreeNode) e.nextElement();
85             if ( child.toString().equals( selDirName)) {
86                 TreePath np = path.pathByAddingChild( child);
87                 makeVisible( np);
88                 setSelectionPath( np);
89                 scrollPathToVisible( np);
90                 break;
91             }
92         }
93         setEnabled( true);
94         return true;
95     }
96
97
98     /**
99      * Inner class that represents a node in this file system tree
100      */

101     protected static class FileTreeNode extends DefaultMutableTreeNode {
102
103         /**
104          * Full pathname of node's representation in file system, endsWith File.separator
105          * Empty for single root node which holds drives
106          */

107         protected String JavaDoc fullName;
108         /**
109          * last part of node's full pathname in file system
110          * and string visible in tree view; empty for single root node which holds drives
111          */

112         protected String JavaDoc name;
113         /**
114          * Description of the Field
115          */

116         protected boolean hasVisibleSubElements;
117         /**
118          * Description of the Field
119          */

120         protected FileTreeElementFilter filter = new FileTreeElementFilter();
121         
122
123         /**
124          * Constructor for the FileTreeNode object
125          *
126          *@param parent Description of Parameter
127          *@param name Description of Parameter
128          */

129         public FileTreeNode( String JavaDoc parent, String JavaDoc name) {
130                 
131             this.name = name;
132             
133             // cases fullName name :
134
// -----------------------------------------------------------------------
135
// root "" ""
136
// drive drive+File.separator drive[+File.separator] (from listRoots())
137
// dir absolutePath+File.separator leafDirName
138

139             fullName = parent == null ? name : parent + name;
140             // neccessary for windows:
141
if (! fullName.endsWith( File.separator)) fullName = fullName + File.separator;
142             if ( name.length() == 0) fullName = "";
143             hasVisibleSubElements = checkVisibleSubElements();
144         }
145
146         /**
147          * Override isLeaf to check whether this is a directory
148          */

149         public boolean isLeaf() {
150             return !hasVisibleSubElements;
151         }
152
153         /**
154          * Override getAllowsChildren to check whether this is a directory
155          */

156         public boolean getAllowsChildren() {
157             return hasVisibleSubElements;
158         }
159
160         /**
161          * For display purposes, we return our own name
162          */

163         public String JavaDoc toString() {
164             if ( name.length() == 0) return "Laufwerke";
165             return name;
166         }
167
168         /**
169          * Check whether this node's path has valid subelements
170          */

171         public boolean checkVisibleSubElements() {
172             // check root for available drives
173
if ( name.length() == 0) {
174                 File[] drives = File.listRoots();
175                 // System.out.println("* checkingROOT");
176
for( int i = 0; i < drives.length; i++) {
177                     String JavaDoc d = drives[i].getPath();
178                     if (! d.endsWith( File.separator)) d = d + File.separator;
179                     // sorry, otherwise windows asks for a medium
180
if ( d.equals("A:"+File.separator)) continue;
181                     if ( d.equals("B:"+File.separator)) continue;
182                     File drive = new File( d);
183                     try {
184                         if ( /* drive.canRead() && */ !drive.isHidden() ) return true;
185                     }
186                     catch ( SecurityException JavaDoc e) {
187                         // System.out.println("* IGNORED " + d);
188
}
189                 }
190                 return false;
191             }
192             
193             // check dir for available subelements
194
File f = new File( fullName);
195             String JavaDoc[] names = new String JavaDoc[] {};
196             // System.out.println("* checkVisibleSubElements of " + f.getPath());
197
try{
198                 if ((! f.isDirectory()) || (! f.canRead())) return false;
199                 names = f.list( filter );
200             }
201             catch (SecurityException JavaDoc e) {
202                 // System.out.println("* COULD NOT LIST " + f.getPath());
203
}
204             for( int i = 0; i < names.length; i++) {
205                 if ( names[i].equals(".") || names[i].equals("..") ) continue;
206                 return true;
207             }
208             return false;
209         }
210         /**
211          * build children from subelements in file system
212          * precondition: hasVisibleSubElements
213          */

214         void populateDirectories() {
215         
216         boolean nodesAdded = false;
217         
218         removeAllChildren();
219         if (! hasVisibleSubElements) return;
220
221             // populate drives for ROOT
222
if ( name.length() == 0) {
223                 File[] drives = File.listRoots();
224                 Arrays.sort( drives);
225                 for( int i = 0; i < drives.length; i++) {
226                     String JavaDoc d = drives[i].getPath();
227                     if (! d.endsWith( File.separator)) d = d + File.separator;
228                     // sorry, otherwise windows asks for a medium
229
if (d.equals("A:"+File.separator)) continue;
230                     if (d.equals("B:"+File.separator)) continue;
231                     File drive = new File( d);
232                     try {
233                         // if ( drive.canRead() && !drive.isHidden() ) {
234
FileTreeNode node = new FileTreeNode( null, drive.getPath());
235                             this.add( node);
236                             nodesAdded = true;
237                         // }
238
}
239                     catch (SecurityException JavaDoc e) { }
240                 }
241             }
242             // populate subelements for driveDirs and standardDirs
243
else {
244                 File f;
245                 f = new File(fullName);
246                 String JavaDoc[] names = f.list( filter ); // Get list of subelements
247
Arrays.sort( names);
248
249                 // Process the directories
250
for (int i = 0; i < names.length; i++) {
251                     String JavaDoc name = names[i];
252                     File d = new File( fullName, name);
253                     FileTreeNode node = new FileTreeNode( fullName, name);
254                     this.add( node);
255                     nodesAdded = true;
256                 }
257             }
258         if (! nodesAdded) hasVisibleSubElements = false;
259         }
260
261     }
262
263     /**
264      * Inner class that handles element selection from file system
265      */

266     protected static class FileTreeElementFilter implements FilenameFilter {
267     /**
268      * Inner class that handles Tree Expansion Events
269      */

270         public boolean accept(File dir, String JavaDoc name) {
271             try{
272                 File f = new File( dir, name);
273                 if ( ( f.isDirectory()) && (! f.isHidden())) { return true; }
274             }
275             catch ( SecurityException JavaDoc e) { }
276             return false;
277         }
278     }
279     
280     protected class TreeExpansionHandler implements TreeExpansionListener {
281     /**
282      * Inner class that handles Tree Expand/Collaps Events
283      */

284
285         public void treeExpanded( TreeExpansionEvent evt) {
286
287             TreePath path = evt.getPath(); // The expanded path
288
JTree tree = ( JTree) evt.getSource(); // The calling tree
289

290             // Get the last component of the path and
291
// arrange to have it fully populated.
292
FileTreeNode node = ( FileTreeNode) path.getLastPathComponent();
293             node.removeAllChildren();
294             node.hasVisibleSubElements = node.checkVisibleSubElements();
295             node.populateDirectories();
296             ( ( DefaultTreeModel) tree.getModel()).nodeStructureChanged(node);
297         }
298
299         public void treeCollapsed(TreeExpansionEvent evt) {
300             System.out.println( "Collaps: " + evt.getPath());
301         }
302     }
303
304     protected class TreeSelectionHandler implements TreeSelectionListener {
305
306         public void valueChanged( TreeSelectionEvent evt) {
307             TreePath path = evt.getPath();
308             String JavaDoc name = getPathName( path);
309             if ( evt.isAddedPath()) selectedPath = name; else selectedPath = null;
310             // System.out.println("selectedPath:'" + ( selectedPath == null ? "" : selectedPath) +"'");
311
}
312
313     }
314     
315 }
316
317
Popular Tags