Search code examples
javaswingjtabledefaulttablemodel

How to refresh a JTable without setting a new table model?


I am trying to refresh a JTable using the DefaultTableModel without accessing the table itself again, but only the existing, but then updated table model.

Yet, I tried to update the table model itself and then notify the model about it (see in the code). For some reason, the table will not update. I do not know, if this is an access problem or if it is just not possible.

//in the Gui_Main class 
private static void addTables(){
   JTable tblMain = new JTable(Util_Tables.dtm);
}

//in the Util_Tables class, if the tables needs to be updated
public static DefaultTableModel dtm;

public static void updateTable(){
   dtm = new DefaultTableModel(data, columns);
   dtm.fireTableDataChanged();
}

Solution

  • So you're basic structure is all over the place. When you create a new instance of DefaultTableModel and assign it to dtm, this won't be reflected by the JTable, as it is still using the instance it first grabbed when it was created.

    Exposing dtm the way you have, opens it up to undesirable modification and voids one of the principles of OO - encapsulation, where the class is responsible for the management of its properties. This is also a reason to reconsider the use of static

    A better start would be to create a getter which returns a single instance of DefaultTableModel, so each call to it is guaranteed to return the same instance of DefaultTableModel and stops any one else from changing the underlying reference

    private static void addTables(){
       JTable tblMain = new JTable(Util_Tables.getModel());
    }
    
    
    //in the Util_Tables class, if the tables needs to be updated
    private DefaultTableModel model;
    public static DefaultTableModel getModel() {
        if (model == null) {
            model = new DefaultTableModel();
        }
    
    }
    

    Okay, so how about updating the model? Well, you need to start by modifying your updateTable method, so it can be used to actually update the model in some meaningful way

    public static void updateTable(Object[][] data, Object[] columnIdentifiers){
       model.setDataVector(data, columnIdentifiers);
    }
    

    The model will then generate the events it needs itself. If you find yourself calling the fireXxx methods yourself, then it's a good indication that you're doing something wrong.