javaswingjtabledefaulttablemodel

JTable Data Refresh Issue


I want to refresh the JTable data by clicking a button.

The problem is that the old data in the JTable can't be removed and the new data are just added into the table. I tried below ways to remove the old data but none of them works.

1. table.setModel(new DefaultTableModel());
2. ((DefaultTableModel)table.getModel()).setRowCount(0);
3. ((DefaultTableModel)table.getModel()).fireTableDataChanged();
4. ((DefaultTableModel)table.getModel()).getDataVector().removeAllElements();
5. table.repaint();
6. model = (DefaultTableModel)table.getModel();
   while(model.getRowCount() > 0) {
       model.removeRow(0);
   }

Solution

  • Having a refresh button for a JTable is very suspect. It makes me think you aren't correctly adding data as JTables should refresh everytime data is added or removed.

    I would verify a couple of things when using a DefaultTableModel:

    1. Make sure to only add data using addRow
    2. Data should only be inserted using insertRow
    3. Remove data using removeRow

    Never modify the internal vectors directly. It won't cause events to fire and you're stuck with a refresh button. I don't know why they even expose it. The JavaDocs should at least specifically warn against this.

    If all else fails, fire up a debugger and see what happens.