Java JTree在显示时复制文件夹
我有一个自定义Jtree,它显示给定文件夹的结构。我的问题是它以某种方式复制了文件夹 例如,给定的文件夹是C:\exampleJava JTree在显示时复制文件夹,java,swing,jtree,Java,Swing,Jtree,我有一个自定义Jtree,它显示给定文件夹的结构。我的问题是它以某种方式复制了文件夹 例如,给定的文件夹是C:\example ->A some1.txt ->B ->C ->A ->A some1.txt ->B ->B ->C ->C 在示例文件夹中,有3个文件夹称为A、B、C JTree应该这样看待它: C:\示例 ->A some1.txt ->B ->C ->A
->A
some1.txt
->B
->C
->A
->A
some1.txt
->B
->B
->C
->C
在示例文件夹中,有3个文件夹称为A、B、C
JTree应该这样看待它:
C:\示例
->A
some1.txt
->B
->C
->A
->A
some1.txt
->B
->B
->C
->C
但它复制了文件夹,因此显示:
C:\示例
->A
some1.txt
->B
->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;
}
您在
addNodes(…)
方法中的递归有问题,请按如下所示进行更改:
DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {
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);
}
curTop.add(node);
}
return curTop;
}
JTree tree = new JTree(addNodes(new DefaultMutableTreeNode(dir), dir));
1) 为了更快地获得更好的帮助,请发布一个(最少完整的可验证示例)。2) 有关工作示例,请参见。