Sunday, May 1, 2011

Not able to highlight the file in JTree

Hi,

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

From stackoverflow
  • JTree.makeVisible() should be what you need.

    Bombe : That depends on the model of your JTree. You can construct a TreePath by specifying the single components that make up the path. Check the documentation.
    : Can u plz give me an example to build the TreePath. I am using DefaultTreeModel. It helps me a lot.
    DR : AFAIK you have to create your own model for this kind of feature.
  • 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()]));
        }
    

0 comments:

Post a Comment