如何从路径到树列出文件和文件夹?

时间:2016-01-18 09:05:54

标签: java swing jtree

我已尝试将该目录列入树

我设置name = "D:/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]);
            }
        }
    }
}

那我怎么解决这个问题?

如果有其他方式修复该代码然后列出到树

会更好

1 个答案:

答案 0 :(得分:1)

要在树中添加节点,您需要调用DefaultMutableTreeNode.addtemp.add(temp2))。调用setParent()不会在树中添加节点。

此外,您需要更改import_data,以便它需要两个参数:目录的File和目录对应的DefaultMutableTreeNode