Component-oriented model for JTree view.

Java Means Business
Business-oriented models for complex Swing apps
Lowell Kaplan
Listing 3. Component-oriented model for JTree view.


import javax.swing.*;
import javax.swing.tree.*;
import java.util.*;

public class QuoteSectorTreeModel extends DefaultTreeModel
                                    implements DataUpdateListener
{
    private MasterDataModel model;
    private DefaultMutableTreeNode root;

    public QuoteSectorTreeModel(MasterDataModel model)
    {
        super(new DefaultMutableTreeNode(“Sectors”));
        root = (DefaultMutableTreeNode)getRoot();
        this.model = model;
        model.addDataUpdateListener(this);
    }

    public void update(boolean add)
    {
        if (add)
        {
            //first remove everything
            root.removeAllChildren();
            //now repopulate from model
            Vector stockQuotes = model.getStockQuotes();
            for (int i=0;i<stockQuotes.size();i++)
            {
                StockQuote quote =
                        (StockQuote)stockQuotes.elementAt(i);
                Sector sector = quote.getStock().getSector();
                addSector(sector);
            }
            nodeStructureChanged(root);
        }
    }

    private DefaultMutableTreeNode addSector(Sector sector)
    {
        if (sector.getParentSector() == null)
        {
            DefaultMutableTreeNode parentNode =
                                addSectorToNode(sector, root);
            return parentNode;
        }
        DefaultMutableTreeNode parentNode =
                                    addSector(sector.getParentSector());
        DefaultMutableTreeNode thisNode =
                                    addSectorToNode(sector, parentNode);
        return thisNode;
    }

    private DefaultMutableTreeNode addSectorToNode(Sector sector,
                                            DefaultMutableTreeNode node)
    {
            //check if already present
            int count = node.getChildCount();
            for (int i=0;i<count;i++)
            {
                DefaultMutableTreeNode child =
                            (DefaultMutableTreeNode)node.getChildAt(i);
                if (child.getUserObject().equals(sector))
                //already there
                    return child;
            }
            //not there, so add it
            DefaultMutableTreeNode child =
                                new DefaultMutableTreeNode(sector);
            node.add(child);
            return child;
    }
}