Component-oriented model for JTable view.

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


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

public class QuoteBySectorTableModel extends AbstractTableModel implements DataUpdateListener
{
    private static final String[] columns = new String[] {“Symbol”,
                                “Sector”, “Last”, “Change”, “Volume”};
    private MasterDataModel model;
    private Sector sector;
    private Vector stockQuotes = new Vector();

    public QuoteBySectorTableModel(MasterDataModel model)
    {
        this.model = model;
        model.addDataUpdateListener(this);
    }

    public void setSector(Sector s)
    {
        this.sector = s;
        update(true);
    }

    public Sector getSector()
    {
        return sector;
    }

    public int getRowCount()
    {
        return stockQuotes.size();
    }

    public int getColumnCount()
    {
        return columns.length;
    }

    public String getColumnName(int column)
    {
        return columns[column];
    }

    public boolean isCellEditable(int row, int column)
    {
        return false;
    }

    public Object getValueAt(int row, int column)
    {
        StockQuote quote = (StockQuote)stockQuotes.elementAt(row);
        switch (column)
        {
            case 0:	return quote.getStock().getSymbol();
            case 1: return quote.getStock().getSector().getSectorName();
            case 2: return String.valueOf(quote.getLastPrice());
            case 3: return String.valueOf(quote.getNetChange());
            case 4: return String.valueOf(quote.getVolume());
            default: return null;
        }
    }

    public void update(boolean add)
    {
        if (add)
        {
            //repopulate model
            stockQuotes.removeAllElements();
            if (sector != null && model != null)
            {
                Vector allStockQuotes = model.getStockQuotes();
                for (int i=0;i<allStockQuotes.size();i++)
                {
                    StockQuote quote =
                            (StockQuote)allStockQuotes.elementAt(i);
                    Sector quoteSector = quote.getStock().getSector();
                    if (quoteSector.equals(sector) ||
                        quoteSector.isAChildSectorOf(sector))
                    {
                        stockQuotes.addElement(quote);
                    }
                }
            }
        }
        this.fireTableDataChanged();
    }
}