Swing (javax.swing)
Creating a tree
/* started:8:08 PM 10/19/99 */
package simple.tree;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.io.*;
import java.util.*;
class FileTreeNode extends DefaultMutableTreeNode{
private String filepath, name;
FileTreeNode(Object o ){ super( o ); }
public void setData(File file ){
try{
filepath = file.getCanonicalPath();
name = file.getName();
//System.out.println(filepath);
} catch ( IOException ioe){ }
}
public void add( FileTreeNode filetreenode ){
super.add(filetreenode);
}
}
public class FileTree{
private void fileRecurse( File f, FileTreeNode ftn ){
FileTreeNode new_ftn;
try{
//associeer f met ftn
ftn.setData( f );
// recurse through branches
if ( f.isDirectory( ) ) {
String list[ ] = f.list( );
Arrays.sort(list);
for (int i = 0; i < list.length; i++){
new_ftn = new FileTreeNode( list[ i ] );
ftn.add( new_ftn );
fileRecurse( new File(f, list[ i ] ), new_ftn );
}
} else { }
} catch ( Exception ioe ){
System.out.println("ERROR in fileRecurse()");
ioe.printStackTrace( );
}
}
private void fillTheTree( ){
if (root==null) { System.out.println("ERROR: no root defined"); System.exit(0);}
try{
System.out.print("Reading file system...");
File file = new File( rootpath );
FileTreeNode ftn = root; //new FileTreeNode( file.getName( ) );
fileRecurse( file, ftn);
System.out.println("READY");
} catch ( Exception ioe){ }
}// end FileTree.fillTheTree( )
private JFrame appframe; // mother frame
private Container container; // her conatiner
private JScrollPane scrollerleft, // contains Tree
scrollerright; // contains other display
private JSplitPane splitpane; // ?
private
FileTreeNode root=null; // the root of the tree
private JTree tree; // the tree
private String rootpath; //pathstring root
FileTree(String rtpath ){
rootpath = rtpath;
// 1. Setup basic frame
appframe = new JFrame("Een simpele filetree");
container = appframe.getContentPane( );
appframe.setSize(400,350);
// 2. Setup tree
// CREATE TREE
// FILL TREE
root = new FileTreeNode( rootpath );
createTheTree( );
fillTheTree( );
// 3. Setup panels
scrollerleft = new JScrollPane(tree); // create left-panel
scrollerright = new JScrollPane(new JPanel( ) ); // create right-panel
// 4. Create splitpanel
splitpane = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, true, scrollerleft, scrollerright );
// 5. Add splitpanel to container
container.add(splitpane);
// 6. Display all
appframe.setVisible( true ); //necessary to get width of spl. pane
splitpane.setDividerLocation( 2*container.getWidth( )/3 );
}
void createTheTree( ){
tree =new JTree(root);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setEditable(true);
}
public static void main(String args[]){
FileTree fileTree;
if ( args.length>0 ){
fileTree = new FileTree( args[0] );
} else {
fileTree = new FileTree("E:\\jdk12\\bin\\classes" );
}
}
}
|