Search code examples
javaswingarraylistjtabledefaulttablemodel

Explicitly writing a Class for inserting Data into JTable Swing


In my Application i wrote a class which inserts data into JTable.

App have two Entities 1: Category 2: Product

For Category I have written this class . When i want to show data in JTable i call any method from this class according to situation.

public class InsertDataToTable {

public void insertCategoriesToTable(JTable tableObject,ArrayList<CategoryEntity> getCategories) {

    DefaultTableModel model = (DefaultTableModel) categoryTable.getModel();
    model.setRowCount(0);
    for (CategoryEntity category : getCategories) {
        int id = category.getId();
        String categoryName = category.getCategoryName();
        model.insertRow(categoryTable.getRowCount(), new Object[]{id, categoryName});
    }

}

public void insertSingleCategory(JTable tableObject,CategoryEntity category){
    DefaultTableModel model = (DefaultTableModel) categoryTable.getModel();
    model.setRowCount(0);     
    int id=category.getId();
    String categoryName=category.getCategoryName(); 
    model.insertRow(categoryTable.getRowCount(), new Object[]{id, categoryName});
}

}

Now I want to make this class General so that I can pass either category object or product object and It Inserts data to table.

Confusion for me is in

public void insertCategoriesToTable(JTable tableObject,ArrayList<CategoryEntity> getCategories)

What should i pass instead of ArrayList so that i can call both methods for both Entities (Category and Product).

I don't want to write same class with little changes for Product Entity.


Solution

  • You might consider writing a custom TableModel implementation that allows you to work with domain objects, either Category or Product or whatever entity you need.

    Take a look to these topics:

    In this way you can add / delete / update domain objects directly to/from the TableModel without any other class: the JTable to which the table model is attached to will be repainted automatically on TableModelEvent's.

    Even if you insist in writing a specific class to do the insertions it could be something like this where T is the type of the entity you want to instert into your table model (not too much benefits though):

    public class InsertDataToTable {
    
        public static <T> void insertToTable(JTable table, List<T> domainObjects) {
            DataObjectTableModel<T> model = (DataObjectTableModel<T>) table.getModel();
            model.clearTableModelData();
            for (T domainObject : domainObject) {
               model.addDataObject(domainObject);
            }
        }
    
        public static <T> void insertSingleObject(JTable table, T domainObject){
            DataObjectTableModel<T> model = (DataObjectTableModel<T>) table.getModel();
            model.clearTableModelData();
            model.addDataObject(domainObject);
        }
    }