gpt4 book ai didi

java - JTable 如何在插入删除或更新数据后刷新表模型。

转载 作者:IT老高 更新时间:2023-10-28 11:38:31 24 4
gpt4 key购买 nike

这是我的 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);
}

目前我在更新表格数据后使用这种方法来刷新表格。我先收拾 table

DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
tableModel.setRowCount(0);

然后再次重构表模型,以便刷新 jTable。但我在想是否有任何最佳实践或更好的方法来做到这一点?

最佳答案

如果您想通知您的 JTable 有关数据的更改,请使用
tableModel.fireTableDataChanged()

来自documentation :

Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.

关于java - JTable 如何在插入删除或更新数据后刷新表模型。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3179136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com