[ Back | Previous | Next ]

How to programmatically select nodes?

Package:
javax.swing.tree.*
Product:
Swing
Release:
1.0.3
Related Links:
DefaultTreeModel
JTree
Comment:
Selecting a tree node using the row number is pretty straightforward. You simply call setSelectionRow() with the
                          problem row number. The problem with this though is that often times the row is not even visible. 

                          The other function setSelectionPath() is more useful but less intuitive to use. It takes a while to figure out how to get
                          the treepath. Here's a sample code snippet for when we have the tree node. 


                          // node is of the type DefaultMutableTreeNode
                          tree.setSelectionPath( new TreePath( node.getPath() ) );

                          // This statement does the exact same thing as that above
                          // Use one or the other - not both
                          tree.setSelectionPath( new TreePath( ((DefaultTreeModel)tree.getModel()).getPathToRoot( node ) ) );
1