TableModel dataModel = new AbstractTableModel() {
public int getRowCount() { return 10; }
public int getColumnCount() { return 10; }
public Object getValueAt( int row, int col ) {
return new Integer(row*col); }
};
JTable table = new JTable( dataModel );
JScrollPane scrollpane = new JScrollPane( table );
There are two supplied implementations of the TableModel
interface: DefaultTableModel, and
AbstractTableModel. The former is a complete
implementation, and the latter is an almost-complete implementation.
What is missing in AbstractTableModel are default
implementations of the following methods:
The example demonstrates a reasonably interesting subset of AbstractTableModel, TableColumn, TableCellRenderer, and TableHeader features/issues.
The first column is alphabetic data and should be left-justified. It also has a "renderer" that manages background color, foreground color, and tool tip text. The second column is numeric data and should be right-justified. The third column is boolean data. It is editable because of the implementation of ArrayBasedDataModel's isCellEditable() method. Because it is boolean and editable and there is a getColumnClass() method in the table model, the default table cell editor will implement it with JCheckBoxes. [The getColumnClass() method was also necessary to get the Integer right-justification to work.]
In the previous example, the table header behavior is the responsibility of a JScrollPane component. In this example, that responsibility has been taken on by the JFrame's content pane's BorderLayout component. See [Topley, p926] if you want to further explore this enigma shrouded in mystery.