I am creating a JTree using the GUI builder in Netbeans and I can add nodes and everything to the tree using the following code
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
}
}
}
then calling it like
listAllFiles("C:\\test", defaultMutableTreeNode , true);
I can add this code to the init() method of the JTree so that when it is built it will have all the folders and files in the Test folder which is grand out, but what i really want to do is add the nodes to the JTree when i click on a button but i cant figure out how to do this! I can add the listAllFiles("C:\\test", defaultMutableTreeNode , true); to the ActionPerformed of the a new button but then it cannot find the defaultMutableTreeNode.
So how would be the best way to do this? would it be to create a new DefaultMutableTreeNode when ever I click the button?
Well i figured out one way to do it but im not too sure if is the best way to do it! I basically create a new DefaultMutableTreeNode in the ActionPerformed of the button and that is populating the tree correctly for me anyway
but would like to see if there is any better ways to do this… coding wise