Y05.java

import java.io.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.*; // for TreeSelectionListener
import java.util.*; // for Enumeration
import java.awt.*;
import java.awt.event.*;

/**
Skeleton of a simple file browser using JTree and JSplitPane.
Includes a listener to trap tree selection events.
*/
public class Y05
{
    public static void main(String argv[])
    {
        JFrame f = new QFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.show();
    }
}

class QFrame extends JFrame
{
    public QFrame()
    {
        setTitle("CISC370-011 -- Tree demo #2");
        setSize(700,500);
        setLocation(50,50);
        Container cp = getContentPane();

        // Our sample tree is built using the default tree model.
        root = makeSampleTree();
        model = new DefaultTreeModel(root);
        tree = new JTree(model);
        tree.setEditable(true);
        JScrollPane spTree = new JScrollPane(tree);

        // A preview pane, suitable for framing.
        final ViewArea va = new ViewArea();
        JScrollPane spPreview = new JScrollPane(va);

        // Display the tree panel and the preview panel in a split pane.
        JSplitPane splitter = 
            new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                spTree,spPreview);
        cp.add(splitter,BorderLayout.CENTER);

        // A panel to contain our control buttons.
        JPanel buttonPanel = new JPanel();

        // A button to view the currently-selected node.
        JButton viewButton = new JButton("View");
        buttonPanel.add(viewButton);
        viewButton.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    DefaultMutableTreeNode selNode = 
                        (DefaultMutableTreeNode)tree.
                            getLastSelectedPathComponent();
                    if (selNode == null ||
                            selNode.getParent() == null)
                        return;
                    Object uo = selNode.getUserObject();
                    va.setFile(((MyObject)uo).getFile());
                }
            });

        // A button to delete the currently-selected node, along
        // with all its children.
        JButton delButton = new JButton("Delete");
        buttonPanel.add(delButton);
        delButton.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    DefaultMutableTreeNode selNode = 
                        (DefaultMutableTreeNode)tree.
                            getLastSelectedPathComponent();
                    if (selNode == null ||
                            selNode.getParent() == null)
                        return;
                    model.removeNodeFromParent(selNode);
                }
            });

        // A button to enumerate (on System.out) the tree 
        // starting at the currently-selected node.
        JButton enumButton = new JButton("Enumerate");
        buttonPanel.add(enumButton);
        enumButton.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    DefaultMutableTreeNode selNode = 
                        (DefaultMutableTreeNode)tree.
                            getLastSelectedPathComponent();
                    if (selNode == null)
                        return;
                    Enumeration pot = 
                        ((DefaultMutableTreeNode)selNode).
                            preorderEnumeration();
                    // Here, we compute the indentation level of
                    // root of the selected node.  We'll indent
                    // other nodes relative to this level.
                    TreeNode[] x = model.getPathToRoot(selNode);
                    int level = x.length;
                    System.out.println();
                    System.out.println("Enumerating...");
                    while (pot.hasMoreElements()) {
                        TreeNode tn = (TreeNode)pot.nextElement();
                        // The next few lines are an inefficient
                        // way to indent each node.  In real code,
                        // we'd never rebuild a path back to the
                        // root for each node we print out.
                        x = model.getPathToRoot(tn);
                        for (int k=0; k<x.length-level; k++)
                            System.out.print("   ");
                        System.out.println(tn);
                        }
                    System.out.println();
                }
            });

        cp.add(buttonPanel,BorderLayout.SOUTH);

        // A listener that prints (to System.out) whenever a node
        // is selected.
        tree.addTreeSelectionListener(
            new TreeSelectionListener()
            {
                public void valueChanged(TreeSelectionEvent e)
                {
                    TreePath[] tp = tree.getSelectionPaths();
                    if (tp == null)
                        return;
                    System.out.println();
                    System.out.println("Tree selection(s):");
                    for (int i=0; i<tp.length; i++)
                        System.out.println("   " + tp[i]);
                }
            });
    }

    /**
    Represents a File for a TreeNode.
    */
    private static class MyObject
    {
        public MyObject(File f)
            { myfile = f; }
        public String toString()
            { return myfile.getName(); }
        public File getFile()
            { return myfile; }
        private File myfile;
    }

    // Data for a sample tree.
    private static TreeNode makeSampleTree()
    {
        DefaultMutableTreeNode root;
        root = new DefaultMutableTreeNode("CIS370 files");
        oneLevel(root,new File("D:\\CIS370\\Code"));
        oneLevel(root,new File("D:\\CIS370\\Web"));
        return root;
    }

    private static void oneLevel(DefaultMutableTreeNode root,File f)
    {
        DefaultMutableTreeNode node;

        node = new DefaultMutableTreeNode(new MyObject(f));
        root.add(node);
        if (f.isDirectory()) {
            File[] files = f.listFiles();
            for (int i=0; i<files.length; i++)
                oneLevel(node,files[i]);
            }
    }

    private JTree tree;
    private TreeNode root;
    private DefaultTreeModel model;
}


/**
A text area for previewing a file.
*/
class ViewArea extends JEditorPane
{
    public ViewArea()
    {
        myfile = null;
        setContentType("text/plain");
        setText("");
        setFont(new Font("Monospaced",Font.PLAIN,11));
    }

    public void setFile(File f)
    {
        try {
            if (f == null)
                setText("");
            else if (f.exists()) {
                if (f.isDirectory())
                    setText("Directory " + f.getCanonicalPath());
                else {
                    String fNAME = f.getName().toLowerCase();
                    if (fNAME.endsWith(".html"))
                        setContentType("text/html");
                    else
                        setContentType("text/plain");
                    if (fNAME.endsWith(".txt") ||
                            fNAME.endsWith(".java") ||
                            fNAME.endsWith(".html")) {
                        FileReader infile = 
                            new FileReader(f);
                        StringBuffer sbuf = new StringBuffer();
                        char[] buf = new char[8192];
                        while (true) {
                            int n = infile.read(buf);
                            if (n <= 0)
                                break;
                            sbuf.append(buf,0,n);
                            }
                        setText(sbuf.toString());
                        setSelectionStart(0);
                        setSelectionEnd(0);
                        }
                    else {
                        setText("");
                        }
                    }
                }
            else
                setText("File " + f.getCanonicalPath() + " not found!");
            }
        catch (IOException eIO) {
            setText("Exception: "+eIO);
            }
    }

    File myfile;
}