Search code examples
javaswingjtabletablemodel

Update JTable when Data changes


The question might been answered already and I read many similar ones but doesn't work for me. So I have my JTable with Custom Table model that extends DefaultTableModel. My data is Object[][] data and Column Names String[] columnNames. So when my data changes how do I update the table? I have been using tableModel.setDataVector(data, columnNames) and it is working but it resets my custom cell renderer to default. Thanks.


Solution

  • Don't change the Arrays! The DefaultTableModel will copy the data from the Arrays to the internal storage used by the DefaultTableModel.

    Instead, you need to change the TableModel directly by using the setValueAt(...) method of the JTable or the TableModel. The TableModel will then notify the table that changes have been made.

    I have been using tableModel.setDataVector(data, columnNames) and it is working but it resets my custom cell renderer to default

    If you need to recreate the entire TableModel for some reason then you can use:

    table.setAutoCreateColumnsFromModel( false );
    

    AFTER you create the table using a TableModel the first time. Now the next time you use the setDataVector(...) method the TableColumnModel of the table will NOT be recreated which means you won't lose the custom renderers.