- 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
The Tree Implementation
Since the tree is just going to display the data model and allow its custom renderer and editor to handle the details of displaying and editing the nodes, almost nothing needs to be done to implement it. The only special task that the tree needs to perform is to ensure that only leaf nodes can be edited. As you saw earlier in this chapter, it is possible to check that the node being edited is a leaf from within the cell editor (refer to "Controlling Editability in the Tree Cell Editor"), but it is simpler to make this check in the JTree isPathEditable method. To override this method, you have to subclass JTree. The code is very simple:
JTree t = new JTree(m) { public boolean isPathEditable(TreePath path) { // Only allow editing of leaf nodes return isEditable() && getModel().isLeaf(path.getLastPathComponent()); } };
This code is general enough that you can use it any time you want to ensure that only leaf nodes can be edited. Note that it uses the TreeModel isLeaf method to perform the test instead of the TreeNode isLeaf method, because the former calls the TreeNode getAllowsChildren method instead of isLeaf if the TreeModel has been set up to require this.