views:

77

answers:

1

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 frist 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?

+2  A: 

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.

Peter Lang
do you mean i call this tableModel.fireTableDataChanged() everytime when i doing updating ?
@newbie123: If you only insert new lines, you can use [fireTableRowsInserted](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/table/AbstractTableModel.html#fireTableRowsInserted%28int,%20int%29) instead. On the other hand, the implementation of `DefaultTableModel.addRow` should already handle that... Isn't your table refreshed by `addRow`?
Peter Lang
I am using addRow it works but how about update?
using setValue?
Use [`setValueAt`](http://java.sun.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html#setValueAt%28java.lang.Object,%20int,%20int%29), `DefaultTableModel` fires the event.
Peter Lang