How does a TableModelListener for a JTable work?

Viewed 2958

It's my first time having to work with a JTable. I pull data from a database via the DAO pattern, save it in a collection, read that collection and fill up my JTable with it. However I'm also working with the MVC pattern and don't know how to properly update my view, so the data added to the JTable actually shows up. I've read about ways to do it via an Observer or TableModelListener (I don't intend to discuss which rather to use). But I cannot find a single complete implementation or in-depth explanation of a working TableModelListener and Oracle docs never have been of much help to me.

Could someone explain to me how to properly implement a TableModelListener for me to update my view once all data has been writing into the JTable?

Here is my AbstractTableModel class:

    public class AbstractTableModel extends DefaultTableModel{

    /**
     * 
     */
    private static final long serialVersionUID = -7354466553311529134L;

    private static Logger logger =     Logger.getLogger(AbstractTableModel.class);

    private static String col[] = { "Table", "UpdateCols", "AlterAuth",
            "DeleteAuth", "IndexAuth", "InsertAuth", "SelectAuth",     "UpdateAuth" };

    private static DefaultTableModel tableModel = new     DefaultTableModel(null, col);
    private static JTable table = new JTable(tableModel);

    public static JTable updateTable(DatenbankDaoImpl db) throws     SQLException, IOException {

        table.getModel().addTableModelListener(new TableModelListener() {

            public void tableChanged(TableModelEvent e) {
                logger.debug(e);
            }
        });

        while (table.getRowCount() > 0) {
            ((DefaultTableModel) table.getModel()).removeRow(0);
        }

        for (DatenbankBean db1 : db.getDatenbank()) {
            String table = db1.getTable();
            String updatecols = db1.getUpdatecols();
            String alterauth = db1.getAlterauth();
            String deleteauth = db1.getDeleteauth();
            String indexauth = db1.getIndexauth();
            String insertauth = db1.getInsertauth();
            String selectauth = db1.getSelectauth();
            String updateauth = db1.getUpdateauth();

            Object[] data = {table, updatecols, alterauth, deleteauth,     indexauth, insertauth, selectauth, updateauth};
            tableModel.addRow(data);
            logger.debug("AbstractTableModel: " + data.toString());
        }
//      table.repaint();
        return table;
    }

}
1 Answers
Related