使用JTree增加,删除,和重命名节点完整实例(三)

2014-11-24 09:21:54 · 作者: · 浏览: 3
eDir(); } }); } else if (evt.getClickCount() == 2) { TreePath path = tree.getSelectionPath(); tree.startEditingAtPath(path); } } }); } /** Remove the currently selected node. */ public void removeCurrentNode() { 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(); } /** Add child to the currently selected node. */ public DefaultMutableTreeNode addObject(Object child) { DefaultMutableTreeNode parentNode = null; TreePath parentPath = tree.getSelectionPath(); if (parentPath == null) { parentNode = rootNode; } else { parentNode = (DefaultMutableTreeNode) (parentPath .getLastPathComponent()); } return addObject(parentNode, child, true); } public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child) { return addObject(parent, child, false); } public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible) { DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child); if (parent == null) { parent = rootNode; } // It is key to invoke this on the TreeModel, and NOT // DefaultMutableTreeNode 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; } class DocTreeModelListener implements TreeModelListener { public void treeNodesChanged(TreeModelEvent e) { TreePath tp = e.getTreePath(); DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) (tp .getLastPathComponent()); /* * If the event lists children, then the changed node is the child * of the node we've already gotten. Otherwise, the changed node and * the specified node are the same. */ int index = e.getChildIndices()[0]; DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode) (parentNode .getChildAt(index)); VEachDir newdir = (VEachDir) changedNode.getUserObject(); dirsList.add(newdir); } public void treeNodesInserted(TreeModelEvent e) { } public void treeNodesRemoved(TreeModelEvent e) { } public void treeStructureChanged(TreeModelEvent e) { System.out.println("treeStructureChanged"); } } private class DocTreeModel extends DefaultTreeModel { private static final long serialVersionUID = 922481109805944053L; public DocTreeModel(TreeNode root) { super(root); } @Override public void valueForPathChanged(TreePath path, Object newValue) { Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()) .getUserObject(); ((VEachDir) obj).setDirName(newValue.toString()); super.valueForPathChanged(path, obj); } } }