Search code examples
javaswingjtree

How to list files and folders from path to tree?


I have tried that code to list directory to tree

I set name = "D:/folder"

folder directory have many files and folders

but all I got as result is one node with name(folder)

public class tree {
    JTree tree;
    DefaultMutableTreeNode node1;
    DefaultMutableTreeNode temp;
    DefaultMutableTreeNode temp2;
    DefaultTreeModel model;
    String name = new currentfolder().getInitial(); // path to directory that its
                                                    // content appear in tree
    public tree() {
        tree = new JTree();
        node1 = new DefaultMutableTreeNode(name);
        temp = node1;
        import_data(new File(name));
        temp.setParent(node1);
        model = new DefaultTreeModel(node1);
        tree.setModel(model);
        model.reload();
        tree.setOpaque(false);
        tree.setBorder(javax.swing.BorderFactory.createCompoundBorder(
          new javax.swing.border.SoftBevelBorder(
          javax.swing.border.BevelBorder.RAISED),
          javax.swing.BorderFactory.createTitledBorder("")));
          tree.setVisible(true);
    }

    public void import_data(File file)    {
        if (file.isFile()) {
            temp2 = new DefaultMutableTreeNode(file.getName());
            temp2.setParent(temp);
            return;
        } else {
            if (file.isDirectory()) {
                if (!file.getName().equals(name)) {
                    temp2 = new DefaultMutableTreeNode(file.getName());
                    temp2.setParent(temp);
                    temp = temp2;
                }
            File[] f = file.listFiles();
            for (int i = 0; i < f.length; i++) {
                import_data(f[i]);
            }
        }
    }
}

so how can I fix that?

it will be better if there is fix for that code else another way then to list to tree


Solution

  • To add a node into the tree, you need to call DefaultMutableTreeNode.add (temp.add(temp2)). Calling setParent() will not add a node into the tree.

    Also you need to change import_data so that it takes two parameters: the File for the directory and the DefaultMutableTreeNode corresponding to the directory.