Jame
Jame

Reputation: 22200

JTree: How to select the first leaf

I am developing a small desktop application in JAVA using Netbeans. I place a JTree and dynamically populating it. Every thing went fine now i want to achieve the following two things:

  1. When the JTree is poupulated it will automatically expanded means it will start showing all of its nodes till the leaf level
  2. The first leaf node should be selected by default.

How do i achieve these two behaviors?

Upvotes: 2

Views: 5487

Answers (1)

Ingo Kegel
Ingo Kegel

Reputation: 48105

Expand all nodes (arbitrary depth):

for (int i = 0; i < tree.getRowCount(); i++) {
    tree.expandRow(i);
}

Select first leaf:

DefaultMutableTreeNode firstLeaf = ((DefaultMutableTreeNode)tree.getModel().getRoot()).getFirstLeaf();
tree.setSelectionPath(new TreePath(firstLeaf.getPath()));

Upvotes: 7

Related Questions