Friday, September 15, 2006

Refresh a JTable from a JDBC connection

I have a Swing application that uses a JTable and JScrollPane to display data from an Access database via a JDBC connection.

Even though I had properly coded the SQL INSERT statement and the data was loading into my database, the JTable was not refreshing with the new record. I tried the .revalidate() and the .repaint() methods to no avail.

Finally, after reading Ben Hendry's Mastering JTable I was able to sort this out.

In my JButton ActionListener I added the TableModel.addRow method and inserted the newly inserted records into the JTable as well. Followed by a .revalidate() and the data properly displayed without even a flicker in my application.

Moral of the story - always use Model-View-Control (MVC) architecture and separate your view from your data and controls.

Mastering the JTable

Hunting around the web looking for a way to "refresh" the JTable that is built from a database connection. I found the Bob Hendry articles which can be seen here. There are quite informative but don't answer the question in full. Still looking:

Mastering the JTable
Using JTable - part one
Using JTable - part two

How to Refresh a JTable in a JScrollPane?

I have created a Swing application that has a JTable with a JScrollPane that is populated with data from an Access database through a JDBC connection.

There are fields where you can add data and insert a record to this database. I am trying to add an event to the JButton so when you click the button and add a new record, that the JTable refreshes and newly queries the data source.

I've searched for how to handle this and tried the revalidate(), repaint() methods and these don't cause a change.