How do I programmatically select a node in a JTree?

By Alvin J. Alexander, devdaily.com

Recently I ran into a programming situation where I needed to select a node in a JTree from my code. As opposed to the usual situation of responding to a user's click on a JTree node, I needed to set the active JTree node based on something that was happening in another area of the application.

Enabling this capability required two parts. First, as I was building the JTree I had to give a controller a reference to a TreePath for each node in the JTree. Second, in another area of the code I used this TreePath reference to select the node programmatically.

The first part of the code looked like this:

  DefaultMutableTreeNode currentCategory = null;
  // do some unrelated things here ...

  node = new DefaultMutableTreeNode(new PanelNode("Edit",
             mainFrameController.getEditSampleController()));
  currentCategory.add(node);
  mainFrameController.getEditSampleController().
             addTreePath(new TreePath(node.getPath()));

As you can see from this code I'm adding the TreePath for the current node to a controller. Then, later on, when something happens in the program that requires me to update the selected node in the tree, I make a call like this:

  myTree.setSelectionPath(treePath);
  myTree.scrollPathToVisible(treePath);

That's all I had to do. The first line sets the selected node in the tree, using the TreePath reference I created earlier. The second method call tells the JTree to scroll if necessary to show the selected node.


devdaily logo