- The Tree Control
- Tree Appearance
- The TreeNode Interface
- The MutableTreeNode Interface
- The DefaultMutableTreeNode Class
- The TreePath Class
- What is a Leaf?
- Tree Expansion and Traversal
- Expanding and Collapsing Nodes under Program Control
- Tree Expansion Events
- Making Nodes Visible
- Controlling Node Expansion and Collapse
- Tree Model Events
- Implementation Plan for the File System Control
- File System Tree Control Implementation
- Using the File System Tree Control
- Custom Tree Rendering and Editing
- Customizing the Default Tree Cell Renderer
- ToolTips and Renderers
- Custom Cell Editors
- Controlling Which Nodes Can Be Edited
- Controlling Editability by Subclassing JTree
- Programmatic Control of Editors
- Editing Trees with Custom User Objects
- The valueForPathChanged Method
- The Tree Implementation
- The Cell Editor
- The Cell Renderer
- Summary
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 = (DefaultMutableTreeNode)apollo11Node.getFirstChild(); path = path.pathByAddingChild(targetNode); t.scrollPathToVisible(path);
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.