Babu R
Babu R

Reputation: 1035

How to automatically open child node after insert into root node in jtree?

When I insert child nodes into root node, the root node is not automatically expanded.

I want to expand root node automatically after insert child nodes into root node.

Thanks in advance..

Upvotes: 1

Views: 2975

Answers (1)

kleopatra
kleopatra

Reputation: 51524

No default automatics, you have to implement it yourself. Several possibilities, all involving a custom TreeModelListener registered to the tree's model. The listener acts on receiving a treeNodesInserted

  • manually expands the JTree to the path
  • set the selection to the path (implicitly expands the tree if its expandsSelectedPaths property is true which is the default)

Code snippet:

class MyTreeModelListener implements TreeModelListener {

     public void treeNodesInserted(TreeModelEvent e) {
          // first option
          myTree.expandPath(e.getPath());
          // second option
          myTree.setSelectionPath(e.getPath());
     }

     // empty implementation of other listener methods
     ...
} 

// usage
myTree.getModel().addTreeModelListener(new MyTreeModelListener());

Upvotes: 6

Related Questions