我想用文件浏览器制作文本编辑器,所以当我启动我的应用程序时,我希望我的程序在 JTree 上添加节点,以便它向我显示所有文件和文件夹,例如在我的文档文件夹中,并让我能够访问这些文件和文件夹(尤其是文件夹)。我试图从这个例子中弄清楚 Andrew Thompson 是如何做到这一点的, 但我失败了。我设法使用此示例为 My Documents 中的所有文件和文件夹创建节点 。但这就是全部,当单击代表文件夹的节点之一时,我无法弄清楚如何为其他文件和文件夹生成节点。
这是我到目前为止所做的:
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
public class MyTextEditor extends JFrame{
JTree tree;
JTabbedPane tabbedPane = new JTabbedPane();
File myDocumentsFolder = new File("C:/Documents and Settings/User/My Documents");
File[] listOfFiles = myDocumentsFolder.listFiles();
String dirTitle = myDocumentsFolder.getName();
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(dirTitle);
DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
public MyTextEditor() {
tree = new JTree(treeModel);
tree.setEditable(false);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,new JScrollPane(tree),tabbedPane);
add(splitPane);
tree.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
for (int i = 0; i < listOfFiles.length; i++) {
String nameOfFile = listOfFiles[i].getName();
rootNode.add(new DefaultMutableTreeNode(nameOfFile));
}
}
});
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable(){
public void run(){
MyTextEditor mte = new MyTextEditor();
mte.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mte.setPreferredSize(new Dimension(800,600));
mte.pack();
mte.setLocationByPlatform(true);
mte.setVisible(true);
}
});
}
}
有人可以告诉我如何为特定文件夹的所有文件和文件夹生成节点。提前致谢。