2012-07-06 34 views
1

我使用NetBeans中的GUI Builder中创建一个JTree,我可以使用下面的代码添加节点和一切树上Netbeans的:GUI构建器的JTree

public static void listAllFiles(String directory, DefaultMutableTreeNode parent, Boolean recursive) { 
      File [] children = new File(directory).listFiles(); // list all the files in the directory 
      for (int i = 0; i < children.length; i++) { // loop through each 
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName()); 
        // only display the node if it isn't a folder, and if this is a recursive call 
        if (children[i].isDirectory() && recursive) { 
          parent.add(node); // add as a child node 
          listAllFiles(children[i].getPath(), node, recursive); // call again for the subdirectory 
        } else if (!children[i].isDirectory()){ // otherwise, if it isn't a directory 
          parent.add(node); // add it as a node and do nothing else 
        } 
      } 
    } 

然后调用它像

listAllFiles("C:\\test", defaultMutableTreeNode , true); 

我可以将此代码添加到JTree的init()方法中,以便在构建它时,它将包含Test文件夹中所有文件夹和文件,但我真正想要做的是将节点添加到JTree当我点击一个按钮,但我不知道如何做到这一点!我可以将listAllFiles("C:\\test", defaultMutableTreeNode , true);添加到新按钮的ActionPerformed,但它不能找到defaultMutableTreeNode

那么如何做到这一点最好的方法?当我点击按钮时是否会创建一个新的DefaultMutableTreeNode

回答

0

嗯,我想出了一种方法来做到这一点,但我不太确定是否是最好的方法来做到这一点!我基本上都是在按钮的actionPerformed创建一个新的DefaultMutableTreeNode和被正确反正填充树对我来说

javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); 
jTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); 
listAllFiles(folderPath, treeNode1, true); 

,但想看看有没有更好的方式来做到这一点...编码明智

相关问题