// 创建滚动条,并将表格放在里面
JScrollPane scrollPane = new JScrollPane(table);
// 将滚动条(包含表格)加入主 Panel
add(scrollPane);
}
// 关键类,继承自 AbstractTableModel
class MyTableModel extends AbstractTableModel {
// 表格的标题
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
// 表格的内容
private Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne",
"Pool", new Integer(10), new Boolean(false)}
};
// 获取列数
public int getColumnCount() {
return columnNames.length;
}
// 获取内容长度
public int getRowCount() {
return data.length;
}
// 获取列名
public String getColumnName(int col) {
return columnNames[col];
}
// 获取单元格数据
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* 获取列编辑器类名
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* 如果表格不可编辑,则不需要实现此方法
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) { //如果列数大于2,则不可编辑,可自由定义
return false;
} else {
return true;
}
}
/*
* 如果表格数据不能改变,则不需要实现此方法
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}