我想在树中显示目录结构:
public static void main(String[] args) {
File sourceDirectory = new File("C:\\myFolder");
DefaultMutableTreeNode sourceRoot = new DefaultMutableTreeNode(sourceDirectory);
DefaultTreeModel sourceModel = new DefaultTreeModel(sourceRoot);
JTree sourceTree = new JTree();
sourceTree.setModel(sourceModel);
sourceTree.setShowsRootHandles(true);
sourceRoot.removeAllChildren();
sourceModel.reload();
File rootFile = (File) sourceRoot.getUserObject();
addFiles(rootFile, sourceModel, sourceRoot);
}
protected void addFiles(File rootFile, DefaultTreeModel model, DefaultMutableTreeNode root) {
for (File file : rootFile.listFiles()) {
DefaultMutableTreeNode child = new DefaultMutableTreeNode(file.getName());
model.insertNodeInto((MutableTreeNode) child, root, root.getChildCount());
if (file.isDirectory()) {
addFiles(file, model, child);
}
}
}
结果就是这些:
但是我想为每个树项添加复选框,我该怎么办?