【发布时间】:2012-07-06 11:23:51
【问题描述】:
我正在使用 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 吗?
【问题讨论】: