Reputation: 11
I have created a JTree in which I want to highlight a file and if the directory containing the file is invisible, I need to expand it.
Ex: I have created a JTree with the root node- D:/Company/abb/src. The file which I want to highlight is - D:/Company/abb/src/bin/help.txt
Please give me some logic to highlight the file help.txt.
Thanks in advance
Upvotes: 1
Views: 653
Reputation: 64026
I have a JTree which represents the file system. Here's my code to cause a specific directory to be selected (and the tree expanded and the view scrolled if required).
JTree fsTree;
void setSelectedPath(String pth) {
TreePath jtp=buildTreePath(new File(pth));
fsTree.setSelectionPath(jtp);
if(fsTree.getSelectionPath()==null) { fsTree.setSelectionRow(0); }
else { fsTree.scrollPathToVisible(jtp); }
}
public TreePath buildTreePath(File dir) {
ArrayList elms=new ArrayList();
do { elms.add(0,dir); } while((dir=dir.getParentFile())!=null);
elms.add(0,root);
return new TreePath(elms.toArray(new File[elms.size()]));
}
Upvotes: 1