Originally posted by dia:
I am using a JTable to display the values from a database. The rows are added dynamically to the JTable depending upon the rows in the ResultSet.
If we want to be a bit more precise, the rows are added dynamically to the Table
Model, not directly to the table.
The values retrieved are based upon the selections made in two combo boxes.
Initially, when I make a selection and display the JTable, the rows are dynamically added and shown. But, when I again change the values in the combo boxes and display the JTable again, the newly retrieved row values are shown but at the end of the previous selections rows i.e. the earlier values are not getting discarded and the new ones are being appended to the end of the earlier rows.
It sounds like you haven't removed the old rows from the TableModel before adding the new rows. The easiest way to do this with DefaultTableModel is to call
setRowCount(0).
I want to know how to refresh a JTable�s contents. I found out that there is a function called �fireTableDataChanged ()� in the DefaultTableModel Class (which is what I�m using) which according to the API, �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.� But I don�t have any listeners for the JTable I am using.
The JTable itself is listening to the TableModel.
What the fireTableDataChanged() method does is notify the JTable(s) that they should be redrawn to reflect changes in the Model, it doesn't actually change the model. DefaultTableModel has other methods that change the model, and these automatically call the
fire___() methods for you, so you shouldn't have to call them yourself. (When I use JTables I usually subclass AbstractTableModel, and I am careful to call the fire methods appropriately. But this is not your situation.)