[java] JTable How to refresh table model after insert delete or update the data.

This is my jTable

private JTable getJTable() {
    String[] colName = { "Name", "Email", "Contact No. 1", "Contact No. 2",
            "Group", "" };
    if (jTable == null) {
        jTable = new JTable() {
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            }
        };
    }
    DefaultTableModel contactTableModel = (DefaultTableModel) jTable
            .getModel();
    contactTableModel.setColumnIdentifiers(colName);
    jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    return jTable;
}

I will call this method to retrieve the data from database and put it into table model

public void setUpTableData() {
    DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
    ArrayList<Contact> list = new ArrayList<Contact>();
    if (!con.equals(""))
        list = sql.getContactListsByGroup(con);
    else
        list = sql.getContactLists();
    for (int i = 0; i < list.size(); i++) {
        String[] data = new String[7];

            data[0] = list.get(i).getName();
            data[1] = list.get(i).getEmail();
            data[2] = list.get(i).getPhone1();
            data[3] = list.get(i).getPhone2();
            data[4] = list.get(i).getGroup();
            data[5] = list.get(i).getId();

        tableModel.addRow(data);
    }
    jTable.setModel(tableModel);
}

Currently I was using this method to refresh the table after updating the table data. I will first clear the table

DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
tableModel.setRowCount(0);

and then restructure the table model again so it will refresh the jTable. But I was thinking is there any best practices or better way to do that?

This question is related to java swing refresh jtable tablemodel

The answer is


If you want to notify your JTable about changes of your data, use
tableModel.fireTableDataChanged()

From the documentation:

Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.


The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed

try this

public void setUpTableData() {
    DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();

    /**
    * additional code.
    **/
    tableModel.setRowCount(0);
    /**/
    ArrayList<Contact> list = new ArrayList<Contact>();
    if (!con.equals(""))
        list = sql.getContactListsByGroup(con);
    else
        list = sql.getContactLists();
    for (int i = 0; i < list.size(); i++) {
        String[] data = new String[7];

        data[0] = list.get(i).getName();
        data[1] = list.get(i).getEmail();
        data[2] = list.get(i).getPhone1();
        data[3] = list.get(i).getPhone2();
        data[4] = list.get(i).getGroup();
        data[5] = list.get(i).getId();

        tableModel.addRow(data);
    }
    jTable.setModel(tableModel);
    /**
    * additional code.
    **/
    tableModel.fireTableDataChanged();
    /**/
}

Would it not be better to use java.util.Observable and java.util.Observer that will cause the table to update?


I did it like this in my Jtable its autorefreshing after 300 ms;

DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
                return false;
            }
};
JTable table = new JTable();

Timer t = new Timer(300, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                addColumns();
                remakeData(set);
                table.setModel(model);
            }
        });
        t.start();

private void addColumns() {
        model.setColumnCount(0);
        model.addColumn("NAME");
            model.addColumn("EMAIL");} 

 private void remakeData(CollectionType< Objects > name) {
    model.setRowCount(0);
    for (CollectionType Objects : name){
    String n = Object.getName();
    String e = Object.getEmail();
    model.insertRow(model.getRowCount(),new Object[] { n,e });
    }}

I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to swing

Calling another method java GUI Read input from a JOptionPane.showInputDialog box Call japplet from jframe Java JTable getting the data of the selected row What does .pack() do? How to add row of data to Jtable from values received from jtextfield and comboboxes How can I check that JButton is pressed? If the isEnable() is not work? Load arrayList data into JTable How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background

Examples related to refresh

How to Refresh a Component in Angular Angular + Material - How to refresh a data source (mat-table) How to Update a Component without refreshing full page - Angular How to reload page the page with pagination in Angular 2? Swift: Reload a View Controller Button that refreshes the page on click Update data on a page without refreshing How to refresh or show immediately in datagridview after inserting? Gradle project refresh failed after Android Studio update Refresh Part of Page (div)

Examples related to jtable

Java JTable getting the data of the selected row How to add row of data to Jtable from values received from jtextfield and comboboxes Load arrayList data into JTable Display calendar to pick a date in java Most simple code to populate JTable from ResultSet JTable - Selected Row click event Programmatically select a row in JTable How to add checkboxes to JTABLE swing Change the background color of a row in a JTable How to add row in JTable?

Examples related to tablemodel

Java JTable getting the data of the selected row JTable How to refresh table model after insert delete or update the data.