This is an old revision of the document!


JTree
Populating Tree
public class TestPane extends JPanel {
 
        private DefaultTreeModel model;
        private JTree tree;
 
        public TestPane() {
            setLayout(new BorderLayout());
 
            tree = new JTree();
            File rootFile = new File(".");
            DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootFile);
            model = new DefaultTreeModel(root);
 
            tree.setModel(model);
            tree.setRootVisible(true);
            tree.setShowsRootHandles(true);
 
            add(new JScrollPane(tree));
 
            JButton load = new JButton("Load");
            add(load, BorderLayout.SOUTH);
 
            load.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
 
                    DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
                    root.removeAllChildren();
                    model.reload();
                    File rootFile = (File) root.getUserObject();
 
                    addFiles(rootFile, model, root);
 
                    tree.expandPath(new TreePath(root));
 
                }
            });
 
        }
 
        protected void addFiles(File rootFile, DefaultTreeModel model, DefaultMutableTreeNode root) {
 
            for (File file : rootFile.listFiles()) {
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(file);
                model.insertNodeInto(child, root, root.getChildCount());
                if (file.isDirectory()) {
                    addFiles(file, model, child);
                }
            }
 
        }
}        

Reference: https://stackoverflow.com/questions/15215578/how-to-build-a-jtree-dynamically