2012-07-06 33 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); 

,但想看看有沒有更好的方式來做到這一點...編碼明智

相關問題