在JTree中只显示目录,可以通过设置TreeModel来实现。以下是实现的步骤:
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class DirectoryTreeModel extends DefaultTreeModel {
public DirectoryTreeModel(DefaultMutableTreeNode root) {
super(root);
}
@Override
public boolean isLeaf(Object node) {
// 判断节点是否为叶子节点
return false;
}
}
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.JTree;
public class Main {
public static void main(String[] args) {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("根目录");
// 添加目录节点
DefaultMutableTreeNode dir1 = new DefaultMutableTreeNode("目录1");
DefaultMutableTreeNode dir2 = new DefaultMutableTreeNode("目录2");
root.add(dir1);
root.add(dir2);
// 添加文件节点
DefaultMutableTreeNode file1 = new DefaultMutableTreeNode("文件1");
DefaultMutableTreeNode file2 = new DefaultMutableTreeNode("文件2");
dir1.add(file1);
dir2.add(file2);
// 创建JTree并设置TreeModel
JTree tree = new JTree(new DirectoryTreeModel(root));
// 显示JTree
// ...
}
}
通过以上步骤,JTree中只会显示目录节点,文件节点将不会显示出来。你可以根据实际需求添加更多的目录节点和文件节点。
领取专属 10元无门槛券
手把手带您无忧上云