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
?