JTree elements display full path
843805Mar 20 2007 — edited Mar 24 2007Hi, from searching the forums this doesn't seem to be a common problem... Therefore I think I'm being a bit special!
I have a JTree which simply displays my filesystem... (Windows, so C:\ is the root.)
I can't for the life of me figure out how to make children folders display only the folder name rather than the entire directory path.
here is my class JFileTree:
public class JFileTree extends JTree {
public JFileTree(File root) {
super();
FileTreeModel model = new FileTreeModel(root);
this.setModel(model);
}
public JFileTree() {
this(new File(System.getProperty("user.home")));
}
private String parsePath(TreePath treePath) {
int pathSize = treePath.getPathCount();
String path = null;
for (int i = 0; i < pathSize; i++) {
if (path == null) {
path = treePath.getPathComponent(i).toString();
System.out.println(treePath.getPathComponent(i).toString());
}
else {
path += File.separatorChar + treePath.getPathComponent(i).toString();
}
}
return path;
}
public String[] getSelectedUrls() {
int treepathAmount = getSelectionCount();
TreePath[] treePaths = getSelectionPaths();
String[] stringSet = new String[treepathAmount];
if (treepathAmount != 0) {
for (int i = 0; i < treepathAmount; i++) {
stringSet[i] = parsePath(treePaths);
}
return stringSet;
}
return null;
}
}
The FileTreeModel class is as follows:
public class FileTreeModel implements TreeModel {
public FileTreeModel(File root) {
this.root = root;
}
public Object getRoot() {
return root;
}
public boolean isLeaf(Object node) {
return ( (File) node).isFile();
}
public int getChildCount(Object parent) {
File[] children = listDirs(parent);
if (children == null)return 0;
return children.length;
}
public Object getChild(Object parent, int index) {
File[] children = listDirs(parent);
if ( (children == null) || (index >= children.length)) {
return null;
}
return new File( (File) parent, children[index].getName());
}
public int getIndexOfChild(Object parent, Object child) {
File[] children = listDirs(parent);
if (children == null)return -1;
String childname = ( (File) child).getName();
for (int i = 0; i < children.length; i++) {
if (childname.equals(children[i])) {
return i;
}
}
return -1;
}
public File[] listDirs(Object parent) {
File[] dirs = ( (File) parent).listFiles();
Vector dirs2 = new Vector();
for (int i = 0; i < Array.getLength(dirs); i++) {
if (dirs[i].isDirectory()) {
dirs2.add(dirs[i]);
}
}
File[] dirs3 = new File[dirs2.size()];
for (int j = 0; j < dirs2.size(); j++) {
dirs3[j] = (File)dirs2.get(j);
}
return dirs3;
}
public void valueForPathChanged(TreePath path, Object newvalue) {}
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
protected File root;
}
Thanks in advance for any help!
John R.