I have the following JTable code:
private JTable fetchJTable() {
String[] col = { "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(col);
jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
return jTable;
}
I will call the fetchJTable() method to retrieve the data from the database and insert it into a
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);
}
With this code, I was using the fetchJTable() method to refresh the table once the data has been inserted and updated. But before refreshing the data, I am trying to clear the table before restructuring the table model:
DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel(); tableModel.setRowCount(0);
Is this the correct way or are there any other standard ways?