Tree Models

Looking at Figure 17-4 you can get an overview of where all the tree pieces come from. As with many of the Swing components you’ve seen already, the models supporting the data for trees play a crucial role in making the component run. Two interfaces are particularly important: TreeModel, which describes how to work with tree data, and TreeSelectionModel, which describes how to select nodes.

The TreeModel Interface

To get started, you need a tree model. The TreeModel interface is the starting point for your model. You don’t have to start from scratch; there is a default implementation (DefaultTreeModel) that you can subclass or just look at for ideas. (We’ll look at this class later in the chapter.)

Property

The TreeModel has one root property, listed in Table 17-1. This read-only property designates the root of a tree: by definition, the node that has no parent. All other nodes in your tree are descendants of this node.

Table 17-1. TreeModel property

Property

Data type

get

is

set

Default value

root

Object

·

   

Events

The tree model uses the TreeModelEvent class defined in the javax.swing.event package. A TreeModelEvent indicates that the tree changed: one or more nodes were added, modified, or deleted. You will find a more detailed discussion in Section 17.6, later in this chapter.

public void addTreeModelListener(TreeModelListener l)public void removeTreeModelListener(TreeModelListener l)

Add or remove listeners interested in receiving tree model events.

Miscellaneous methods ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.