这是我为表创建的示例模型。
public class CustomModel extends AbstractTableModel {
private Object[] colNames ={"ID","Title", "Author", "Status", "Date Read"};
private LinkedHashSet<CustomClass> data;
public TableModelTop() {
this.data = getDataForDropList();
}
public int getRowCount() {
return data.size();
}
public int getColumnCount() {
return colNames.length;
}
@Override
public String getColumnName(int columnIndex) {
return (String) colNames[columnIndex];
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// Set Values here;
}
public Object getValueAt(int rowIndex, int columnIndex) {
// Get row Values here;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
// Depending on the type of the column. Return data type;
}
/**
* Populate the data from here.
* @return LinkedHashSet<CustomClass>
*/
private LinkedHashSet<CustomClass> getDataForDropList() {
LinkedHashSet<CustomClass> modelList = new LinkedHashSet<CustomClass>();
for(int i = 0; i< 5; i++) {
// Create custom Object and add them to the LinkedHashSet.
// Create a CustomClass object and add it to the LinkedHashSet
modelList.add(customClassObject);
}
// Finally return the llinkedhashset
return modelList;
}
}
在此之后只需调用表模型并将其分配给 JTable。
JTable table = new JTable(new CustomModel());