I want to make a text editor with a file browser, so when I launch my application, I want my program to add nodes to JTree, so it shows me all the files and folders, for example, in the "My Documents" folder and gives me access to these files and folders (especially folders). I tried to figure out how Andrew Thompson made it from this example but I failed. I managed to create nodes for all files and folders from My Documents using this example , but that's all, I canβt figure out how to create nodes for other files and folders by clicking on one of the nodes representing the folder.
This is what I have done so far:
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); } }); } }
Can someone tell me how to create nodes for all files and folders for a specific folder. Thanks in advance.
source share