Found this nice sample program illustrating the use of a TableModel.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class TableExample extends JFrame
{
public TableExample()
{
//headers for the table
String[] columns = new String[] {
"Id", "Name", "Hourly Rate", "Part Time"
};
//actual data for the table in a 2d array
Object[][] data = new Object[][] {
{1, "John", 40.0, false },
{2, "Rambo", 70.0, false },
{3, "Zorro", 60.0, true },
};
final Class[] columnClass = new Class[] {Integer.class, String.class, Double.class, Boolean.class};
//create table model with data
DefaultTableModel model = new DefaultTableModel(data, columns) {
@Override
public boolean isCellEditable(int row, int column)
{
System.out.println("Inside isCellEditable("+ row +","+ column + ")");
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
System.out.println("Inside getColumnClass("+ columnIndex +")");
return columnClass[columnIndex];
}
};
JTable table = new JTable(model);
//add the table to the frame
this.add(new JScrollPane(table));
this.setTitle("Table Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TableExample();
}
});
}
}
System.out.println statements were added and noticed when the application loaded it produced the following output :
Inside getColumnClass(0)
Inside getColumnClass(1)
Inside getColumnClass(2)
Inside getColumnClass(3)
Inside getColumnClass(0)
Inside getColumnClass(1)
Inside getColumnClass(2)
Inside getColumnClass(3)
Inside getColumnClass(0)
Inside getColumnClass(1)
Inside getColumnClass(2)
Inside getColumnClass(3)
Inside getColumnClass(0)
Inside getColumnClass(1)
Inside getColumnClass(2)
Inside getColumnClass(3)
Inside getColumnClass(0)
Inside getColumnClass(1)
Inside getColumnClass(2)
Inside getColumnClass(3)
Inside getColumnClass(0)
Inside getColumnClass(1)
Inside getColumnClass(2)
Inside getColumnClass(3)
There are 4 columns and 3 rows and expected the getColumnClass to execute 12 times. Essentially executing 4 times (one for each column) and 3 times for each row.
There are actually 6 iterations and not 3. Hmmm, so maybe it executes once for the column headers, but that still leaves 2 extra iterations. Maybe it also executes for the blank row at the end, but then that still leaves 1 extra.
Why are there more iterations than expected?