AbstractTableModel 包含三个需要被覆盖的方法。它们是:
public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row, int column);
JTable 使用这些方法来找出有多少字段(行和列)并获取每个字段的值(作为对象类型)。当您覆盖这些方法时,由您决定要使用哪种数据类型。例如,您可以使用二维 Object 数组:
Object[][] data;
或数组的ArrayList:
List<Object[]> data = new ArrayList<Object[]>();
固定大小的数组可能更易于使用,但动态添加值更困难。当然,您也可以使用 Maps 或其他数据结构。您只需要调整上述三种方法的实现,即可从数据结构中返回正确的信息,例如您的模型当前包含多少行等。
还有一些方法可以被覆盖,但不是必须的。例如,如果您想要自定义列名,则必须另外覆盖 public String getColumnName(int col) 方法。
例如这样:
private static final String[] COLUMN_NAMES = {"User", "Password", "Age"};
public String getColumnName(int col) {
return COLUMN_NAMES[col];
}
查看 AbstractTableModel 的 Javadoc 以了解可被覆盖的其他方法的概述。
如果您希望能够更改 TableModel 中的数据,那么您需要覆盖 setValueAt 方法(如果我没记错的话):
void setValueAt(Object aValue, int rowIndex, int columnIndex) {
//depending on your data structure add the aValue object to the specified
//rowIndex and columnIndex position in your data object
//notify the JTable object:
fireTableCellUpdated(row, col);
}
重要提示:无论何时添加或删除一行,TableModel 实现中的相应函数都必须调用相应的 fireTableRowsInserted(或删除)函数。否则你会看到你的 JTable 出现奇怪的视觉效果:
public void addRow(Object[] dates) {
data.add(dates);
int row = data.indexOf(dates);
for(int column = 0; column < dates.length; column++) {
fireTableCellUpdated(row, column);
}
fireTableRowsInserted(row, row);
}