-
JTree only display .txt
Ok, so I have a JTree that I use to display files that are on my computer. Is there a way to make it display only .java files and directories? I made it so that it will only display them, but for every other file, it leaves a blank space where the file is.
here is my getChild()
Code:
public Object getChild(Object parent, int index) {
File directory = (File) parent;
String[] children = directory.list();
if (((children[index].length() >= 5) && children[index].substring(children[index].length()-4).equals("java")) || (new File(directory, children[index]).isDirectory()))
{
return new TreeFile(directory, children[index]);
}
return new TreeFile(directory, "NULL");
}
I don't know if what I tried was in the wrong direction or what I have to do to make it work.
I am trying to edit the code from File System Tree : Tree*«*Swing JFC*«*Java to make it only display .java files
-
IMO this is a better example of a tree at play ...
"java.sun.com/docs/books/tutorial/uiswing/examples/components/TreeDemoProject/src/components/TreeDemo.java"
Just remove the books and create a recursive function to crawl through your file system from a root node, something like ...
Code:
public DefaultMutableTreeNode buildtree(String rootOfFileSystem){
File myFile = new File(rootOfFileSystem);
File[] myFileList = myFile.list();
for (int i=0;i<myFileList.length;i++){
if (myFileList[i].isDirecotry){
create new node
this.buildtree(myFileList[i].absolutePath());
else
// create new leaf
// add to node if it has a .java extention
// Id be inclinded to use substring by "." to figure out if its .java but thats just me
//then add node to root when its on its last iteration ...
}
}
not sure if this will help, but thats my take on it ...sorry i cant post links and the code is pseudo at times, I cant remeber the syntax and I dont have a compiler in front of me .
-
The problem lies in
Code:
return new TreeFile(directory, "NULL");
This will indeed create a blank line in the visible tree.
To solve the problem in the TreeModel, both getChild and getChildCount must be implemented.
getChildCount needs to preprocess directory.list() and count the number of children to be reported.
That is, count the number of .java and isDirectory children.
Then getChild(parent, index) needs to scan through directory.list()
and return the index'th item which is a .java or directory.