简体   繁体   中英

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..

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM