JTable如何在插入删除或更新数据后刷新表模型。这是我的jTableprivate 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。但我在想是否有最好的做法或更好的方法呢?
3 回答
摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
更快的方法是:
jTable.repaint(); // Repaint all the component (all Cells).
当一个或几个细胞改变时的优化方式:
((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.
Helenr
TA贡献1780条经验 获得超4个赞
试试这个
public void setUpTableData() { DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel(); /** * additional code. **/ tableModel.setRowCount(0); /**/ 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); /** * additional code. **/ tableModel.fireTableDataChanged(); /**/}
添加回答
举报
0/150
提交
取消