发现这个很好的示例程序,说明了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语句,并在加载应用程序时注意到它产生了以下输出:
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)
有4列3行,期望getColumnClass执行12次。基本上执行4次(每列一次)和每行3次。
实际上有6次迭代,而不是3次。 嗯,所以它可能会对列标题执行一次,但仍然会留下2次额外的迭代。也许它也会在最后的空行中执行,但那时仍然会留下1个额外的行。
为什么迭代次数多于预期?