mrjasmin
mrjasmin

Reputation: 1270

Java JTree - setSeelectionPath

I want to select a node in my JTree from my code. I am calling the method setSelectionPath but nothing happens. What is wrong with my code ?

public class test extends JFrame {

   private static DefaultMutableTreeNode  root, light, medium, dark, whiteNode;  

   private  static JTree tree;

   public static void main(String[] args){

    new test();

    tree.setSelectionPath(new TreePath(whiteNode.getPath()));



   }

   public test(){


      root = new DefaultMutableTreeNode("colors");

      tree = new JTree(root);


      light =  addFile("light", root); 
      medium = addFile("medium", root);
      dark = addFile("dark", root);

      //Add leaf nodes to light
      whiteNode = addFile("white", light);

      //Add leaf nodes to medium
      addFile("green", medium); 
      addFile("yellow", light);
      addFile("orange", light);
      addFile("violet", light); 

     this.getContentPane().add(tree);
     this.setVisible(true);
     this.validate();
     this.validateTree();

   }


    private DefaultMutableTreeNode addFile(String fname, DefaultMutableTreeNode parentFolder){

    DefaultMutableTreeNode newFile = new DefaultMutableTreeNode(fname);
    parentFolder.add(newFile);

    return newFile; 

}

}

Thanks in advance

Upvotes: 0

Views: 276

Answers (1)

Reimeus
Reimeus

Reputation: 159874

The reference used by the constructor in this statement

TreePath t = new TreePath("colors, light, white");

needs to refer to the last path component and should be of type TreePath rather than a String:

tree.setSelectionPath(new TreePath(whiteNode.getPath()));

where whiteNode is assigned

whiteNode = addFile("white", light);

Read: How to Use Trees

Upvotes: 2

Related Questions