Java JTree example - select a JTree node

Recently I ran into a programming situation where I needed to select a node in a Java 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 JTree node. Second, in another area of the code I used this TreePath reference to select the node programmatically.

The first part of my Java JTree 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 JTree node to my Java controller. Then, later on, when something happens in the program that requires me to update the selected JTree node, 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 JTree node, using the TreePath reference I created earlier. The second method call tells the JTree to scroll if necessary to show the selected node.