Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

Making Nodes Visible

When you change the state of a tree programmatically, it is sometimes useful to have the tree scroll so that the user can see the affected area. In the example that you have just seen, the frame was large enough so that the whole tree was visible after it was expanded to show the node for Neil Armstrong. However, if you run the example again and make the window so short that you can only see the root node, when the tree expands you won't be able to see what has happened.

If you want to force a particular node to be visible, there are two JTree methods that you can use:

public void scrollPathToVisible(TreePath path); 
public void scrollRowToVisible(int row); 

Naturally, these methods only work if the tree is mounted in a JScroll-Pane and they have no effect if the node specified is already within the visible area of the JScrollPane. The following command runs an improved version of the previous example that forces the node for Neil Armstrong into view once its parent node has been expanded:

java JFCBook.Chapter10.TreeExample4 

The code to do this was added after the expandPath call and looks like this:

// Make Neil Armstrong node visible
DefaultMutableTreeNode targetNode = 
path = path.pathByAddingChild(targetNode); 

You'll notice that, since we already had a TreePath object for the parent of the node that we wanted to reach, we were able to use the TreePath pathByAddingChild method to get a TreePath for the Neil Armstrong node, once we obtained its DefaultMutableTreeNode. To demonstrate that this works, when the example starts, resize the window so that it is tall enough to show only the root node and then wait for the tree to expand itself. When it does so, you'll see that it also scrolls to bring Neil Armstrong into view. Incidentally, the scrollPathToVisible method can cause both horizontal and vertical scrolling, so if the window were also very narrow, it would scroll horizontally to bring the node into view if necessary.

  • + Share This
  • 🔖 Save To Your Account