title: Java: How to programmatically select and expand multiple nodes in a JTree?
body: <p>I have a <code>JTree</code> and an <code>awt.Canvas</code>. When i select multiple objects from within the <code>Canvas</code> into the <code>objList</code>, I want all the selected items to be shown inside the <code>JTree</code> as selected. That means for example if I have 2 objects selected, both their paths to root should be expanded, and also each selected object should have its corresponding <code>TreeNode</code> selected. My JTree has <code>TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION</code>.</p>
  
  <p>Here is a sample of the expand funcion i use : </p>
  
  <pre><code>public void selectTreeNodes() {
  
  
      HashMap &lt;String, MyEntity&gt; entities = ...;
      Iterator it = entities.keySet().iterator();
      while (it.hasNext()) {
  
          String str = it.next().toString();
          MyEntity ent = entities.get(str);
  
          if (ent.isSelected()) {
              DefaultMutableTreeNode searchNode = searchNode(ent.getName());
              if (searchNode != null) {
  
                  TreeNode[] nodes = ((DefaultTreeModel) tree.getModel()).getPathToRoot(searchNode);
                  TreePath tpath = new TreePath(nodes);
                  tree.scrollPathToVisible(tpath);
                  tree.setSelectionPath(tpath);
              }
          }
      }
  }
  
  public DefaultMutableTreeNode searchNode(String nodeStr) 
  { 
      DefaultMutableTreeNode node = null; 
  
      Enumeration enumeration= root.breadthFirstEnumeration(); 
      while(enumeration.hasMoreElements()) {
  
          node = (DefaultMutableTreeNode)enumeration.nextElement(); 
          if(nodeStr.equals(node.getUserObject().toString())) {
  
              return node;                          
          } 
      } 
  
      //tree node with string node found return null 
      return null; 
  }
  </code></pre>
  
  <p>In my current state, if I select a single object, it will be selected in the <code>JTree</code> and its <code>TreePath</code> will be shown.
  But if <code>entities</code> has more than 1 object selected, it will display nothing, my <code>JTree</code> will remain unchanged.</p>