package com.ketherware.models; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SalesTotalListModelFilter extends AbstractListModelFilter { protected String totalElement; public SalesTotalListModelFilter(ListModel delegate) { super(delegate); // Calculate the total sales across all elements int total = 0; for (int z = 0; z < delegate.getSize(); z++) { Territory terr = (Territory) delegate.getElementAt(z); total += terr.sales; } totalElement = "*** Total Sales: " + Integer.toString(total); } public int getSize() { // Add one to the delegate size to reserve a // place for the total return delegate.getSize() + 1; } public Object getElementAt(int index) { // If the index is within the delegate, return the // value. Otherwise return the ‘total’ string we // calculated in the constructor if (index < delegate.getSize()) { Territory terr = (Territory) delegate.getElementAt(index); String element = terr.name + " - " + Integer.toString(terr.sales); return element; } return totalElement; } } class TotalTestFrame extends JFrame { JList territoryList = new JList(); TerritoryListModel model = new TerritoryListModel(); SalesTotalListModelFilter inclusionFilter = new SalesTotalListModelFilter(model); public static void main(String[] args) { new TotalTestFrame().setVisible(true); } TotalTestFrame() { super("Sales Figures"); this.setSize(350, 200); this.setLocation(150, 150); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Add the list in a scroll pane and set the // model of the list to be the inclusion filter this.getContentPane().add(new JScrollPane(territoryList), BorderLayout.CENTER); territoryList.setFont(new Font("Arial", Font.BOLD, 14)); territoryList.setModel(inclusionFilter); } }