这是我的jTable
private JTable getJTable() {
String[] colName = { "Name", "Email", "Contact No. 1", "Contact No. 2",
"Group", "" };
if (jTable == null) {
jTable = new JTable() {
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
}
DefaultTableModel contactTableModel = (DefaultTableModel) jTable
.getModel();
contactTableModel.setColumnIdentifiers(colName);
jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
return jTable;
}
我将调用此方法从数据库中检索数据并将其放入表模型中
public void setUpTableData() {
DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
ArrayList<Contact> list = new ArrayList<Contact>();
if (!con.equals(""))
list = sql.getContactListsByGroup(con);
else
list = sql.getContactLists();
for (int i = 0; i < list.size(); i++) {
String[] data = new String[7];
data[0] = list.get(i).getName();
data[1] = list.get(i).getEmail();
data[2] = list.get(i).getPhone1();
data[3] = list.get(i).getPhone2();
data[4] = list.get(i).getGroup();
data[5] = list.get(i).getId();
tableModel.addRow(data);
}
jTable.setModel(tableModel);
}
当前,我在更新表数据后使用此方法刷新表。我先清理桌子
DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
tableModel.setRowCount(0);
然后再次重组表模型,以便刷新jTable。但是我在想是否有最佳实践或更好的方法?