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. We’ll be looking at the model for the tree data first, and later the model supporting tree selections.

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 you can subclass or just look at for ideas. (We’ll look at this class, DefaultTreeModel, 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 will be descendants of this node.

Table 17-1. TreeModel Property

Property

Data Type

get

is

set

bound

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 has been changed; one or more nodes have been added, modified, or deleted. You will find a more detailed discussion of the tree events in Table 17.9 later in this chapter.

public void addTreeModelListener(TreeModelListener ...

Get Java Swing 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.