FileDocCategorySizeDatePackage
DynamicTree.javaAPI DocExample4244Tue Dec 12 18:59:18 GMT 2000None

DynamicTree

public class DynamicTree extends JPanel

Fields Summary
protected DefaultMutableTreeNode
rootNode
protected DefaultTreeModel
treeModel
protected JTree
tree
private Toolkit
toolkit
Constructors Summary
public DynamicTree()


      
        rootNode = new DefaultMutableTreeNode("Root Node");
        treeModel = new DefaultTreeModel(rootNode);
        treeModel.addTreeModelListener(new MyTreeModelListener());

        tree = new JTree(treeModel);
        tree.setEditable(true);
        tree.getSelectionModel().setSelectionMode
                (TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.setShowsRootHandles(true);

        JScrollPane scrollPane = new JScrollPane(tree);
        setLayout(new GridLayout(1,0));
        add(scrollPane);
    
Methods Summary
public javax.swing.tree.DefaultMutableTreeNodeaddObject(java.lang.Object child)
Add child to the currently selected node.

        DefaultMutableTreeNode parentNode = null;
        TreePath parentPath = tree.getSelectionPath();

        if (parentPath == null) {
            parentNode = rootNode;
        } else {
            parentNode = (DefaultMutableTreeNode)
                         (parentPath.getLastPathComponent());
        }

        return addObject(parentNode, child, true);
    
public javax.swing.tree.DefaultMutableTreeNodeaddObject(javax.swing.tree.DefaultMutableTreeNode parent, java.lang.Object child)

        return addObject(parent, child, false);
    
public javax.swing.tree.DefaultMutableTreeNodeaddObject(javax.swing.tree.DefaultMutableTreeNode parent, java.lang.Object child, boolean shouldBeVisible)

        DefaultMutableTreeNode childNode = 
                new DefaultMutableTreeNode(child);

        if (parent == null) {
            parent = rootNode;
        }

        treeModel.insertNodeInto(childNode, parent, 
                                 parent.getChildCount());

        // Make sure the user can see the lovely new node.
        if (shouldBeVisible) {
            tree.scrollPathToVisible(new TreePath(childNode.getPath()));
        }
        return childNode;
    
public voidclear()
Remove all nodes except the root node.

        rootNode.removeAllChildren();
        treeModel.reload();
    
public voidremoveCurrentNode()
Remove the currently selected node.

        TreePath currentSelection = tree.getSelectionPath();
        if (currentSelection != null) {
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                         (currentSelection.getLastPathComponent());
            MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
            if (parent != null) {
                treeModel.removeNodeFromParent(currentNode);
                return;
            }
        } 

        // Either there was no selection, or the root was selected.
        toolkit.beep();