Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

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() &&

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.

  • + Share This
  • 🔖 Save To Your Account