JTable (continued)

All JFC Swing components follow the MVC architecture. To use JTable in the manner it was intended to be used, the programmer should create a TableModel and pass that object to JTable's constructor. For example, to set up a table with 10 rows and 10 columns of Integer objects, do something like:
   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: Even though AbstractTableModel is not a complete implementation, you are more likely to use it to create table models, because it is easier to work with and is probably more convenient if you get your data from an external source rather than hard-coding it into your application. [Topley, p886]

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.