MutableTreeNode node = (MutableTreeNode) path .getLastPathComponent();
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
if (node.getAllowsChildren()) {
String Name = JOptionPane.showInputDialog(null, \创建目录名称:\);
if (!Name.equals(\)) {
MutableTreeNode newNode = new
DefaultMutableTreeNode(Name);// 建立新节点
1);
+ Name);
tree.fireTreeExpanded(path);
model.insertNodeInto(newNode, node, 0); String fullPath = \;
for (Object obj : path.getPath()) { String str = obj.toString(); if (str.endsWith(\))
str = str.substring(0, str.length() -
if (fullPath.equals(\)) fullPath += str; else
fullPath += \ + str; }
File parentDir = new File(fullPath); if (parentDir.isDirectory()) { File currentFile = new File(fullPath + \ currentFile.mkdir(); }
} else {
JOptionPane.showMessageDialog(null, \目录名不
能为空\);
} else {
}
11
JOptionPane.showMessageDialog(null, \不能给文件
追加下级目录!\); return;
} } }
新建目录如图8所示,
图8 新建目录
3.4新建文件实现
新建文件主要代码:
private class NewFileAction implements ActionListener { public void actionPerformed(ActionEvent e) {
12
TreePath path = tree.getSelectionPath(); MutableTreeNode node = (MutableTreeNode) path .getLastPathComponent(); if (node.getAllowsChildren()) {
String fullPath = \;
for (Object obj : path.getPath()) { String str = obj.toString(); if (str.endsWith(\))
str = str.substring(0, str.length() - 1); if (fullPath.equals(\)) fullPath += str; else
fullPath += \ + str; }
String FileName =
JOptionPane.showInputDialog(null, \创建文件名称:\);
if (!FileName.equals(null)) { File f = new File(fullPath + \ + FileName); try {
f.createNewFile();
} catch (IOException e1) { e1.printStackTrace(); } } else {
JOptionPane.showMessageDialog(null, \不能添加
文件!\); return;
} } } }
13
新建文件如图9所示,
图9 新建文件
3.5删除文件实现
删除文件主要代码:
private class DeleteAction implements ActionListener{
public void actionPerformed(ActionEvent e) { TreePath tp = tree.getSelectionPath(); DefaultMutableTreeNode node =
(DefaultMutableTreeNode) tp.getLastPathComponent();
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
14

