【发布时间】:2014-11-05 12:40:29
【问题描述】:
我有一个自定义的 Jtree,它显示了给定文件夹的结构。我的问题是它以某种方式重复了文件夹。
例如给定的文件夹是 C:\Example
在示例文件夹中有 3 个文件夹,分别称为 A、B、C
JTree 应该像这样查看它:
C:\示例
->A
some1.txt
->B
->C
但它复制了文件夹,所以它显示:
C:\示例
->A
->A
some1.txt
->B
->B
->C
->C
我使用自定义渲染器只显示名称而不是 jtree 中的完整路径, 在这里:
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
System.out.println(value);
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
value = ((DefaultMutableTreeNode)value).getUserObject();
if (value instanceof File) {
File file = (File) value;
if (file.isFile()) {
setText(file.getName());
} else {
setText(file.getName());
}
}
}
return this;
}
这里是我用数据填充 Jtree 的地方:
/**
* Add nodes from under "dir" into curTop. Highly recursive.
*/
DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {
DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(dir);
if (curTop != null) { // should only be null at root
curTop.add(curDir);
}
File[] tmp = dir.listFiles();
Vector<File> ol = new Vector<File>();
ol.addAll(Arrays.asList(tmp));
Collections.sort(ol, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
int result = o1.getName().compareTo(o2.getName());
if (o1.isDirectory() && o2.isFile()) {
result = -1;
} else if (o2.isDirectory() && o1.isFile()) {
result = 1;
}
return result;
}
});
// Pass two: for files.
for (int fnum = 0; fnum < ol.size(); fnum++) {
File file = ol.elementAt(fnum);
DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);
if (file.isDirectory()) {
addNodes(node, file);
}
curDir.add(node);
}
return curDir;
}
这是我在代码中使用这些的地方:
dir = new File(System.getProperty("user.dir")+"\\Example");
tree = new JTree(addNodes(null, dir));
tree.setCellRenderer(new MyTreeCellRenderer());
【问题讨论】:
-
1) 为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)。 2) 有关工作示例,请参阅File Browser GUI。