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
?