Tree Model

From Documentation
Revision as of 07:58, 6 January 2011 by Tomyeh (talk | contribs)

Here we describe how to implement a tree model (TreeModel). For the concept about component, model and render, please refer to the Model-driven Display section.

A tree model is used to control how to display a tree-like component, such as Tree.

Instead of implementing TreeModel from scratch, it is suggested to extend from AbstractTreeModel, which will handle the data listeners transparently, while it allows the maximal flexibility, such as load-on-demand and caching.

In additions, if the tree is small enough to be loaded completely, you could use the default implementation, DefaultTreeModel, which uses DefaultTreeNode to construct a tree[1].

Example: Load-on-Demain Tree with AbstractTreeModel

Implementing all TreeModel directly provides the maximal flexibility, such as load-on-demand and caching. For example, you don't have to load a node until TreeModel.getChild(Object, int) is called. In additions, you could load and cache all children of a given node when TreeModel.getChild(Object, int) is called first time against a particular node, and then return a child directly if it is in the cache.

Here is a simple example, which generates a four-level tree and each branch has five children:

public class FooModel extends AbstractTreeModel {
    public FooModel() {
        super("Root");
    }
    public boolean isLeaf(Object node) {
        return getLevel((String)node) >= 4; //at most 4 levels
    }
    public Object getChild(Object parent, int index) {
        return parent + "." + index;
    }
    public int getChildCount(Object parent) {
        return 5; //each node has 5 children
    }
    public int getIndexOfChild(Object parent, Object child) {
        String data = (String)child;
        int i = data.lastIndexOf('.');
        return Integer.parseInt(data.substring(i + 1));
    }
    private int getLevel(String data) {
        for (int i = -1, level = 0;; ++level)
            if ((i = data.indexOf('.', i + 1)) < 0)
                return level;
    }
};

As shown, you have to implement four methods: TreeModel.getChild(Object, int), TreeModel.getChildCount(Object), TreeModel.getIndexOfChild(Object, langObject) and TreeModel.isLeaf(Object).

Example: Stationary Tree with DefaultTreeModel


  1. DefaultTreeModel was available in 5.0.6. For 5.0.5 or prior, please use SimpleModel, which is similar except it assumes the tree structure is immutable

Version History

Last Update : 2011/01/06


Version Date Content
5.0.6 January 2011 TreeNode, DefaultTreeNode and DefaultTreeModel were intrdocued.



Last Update : 2011/01/06

Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.