Question

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);
   }
Was it helpful?

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.

OTHER TIPS

More of your code might be appropriate here. Hard to tell exactly where you're calling these methods and the order. If you change the model and then call fireTableDataChanged() it should work....assuming you've updated the right TableModel. There is a good Java tutorial for using tables: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

Had the same issue myself, but my solution was different. After checking just about everything, I checked the contents of the table via the console, and found that the contents were indeed being updated. However, the update was not being reflected on the table which was visible on the screen.

In fact, this code:

model = (DefaultTableModel)table.getModel();


while(model.getRowCount() > 0) {
       model.removeRow(0);
   }

Did not only remove the rows, but also removed the table.

My solution was to remove the table from the form and then re-add it, whenever the table data was changed.

Seemed in my case there was nothing wrong with my coding to generate the table but that the layout manager didn't like overwriting or updating a component the area where I wanted to put it already had something in there.

Something weird going on methinks but at the end of the day this worked for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top