Two Laptop Bag
The moose likes JDBC and Relational Databases and the fly likes JTable not refreshing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "JTable not refreshing " Watch "JTable not refreshing " New topic

JTable not refreshing

Ayo Babatope

Joined: Jan 17, 2013
Posts: 2
My Jtable is not refreshing itself automatically when its data in the database to which it is connected to changed.

But it will refresh when I restart the application.

I'm using my own TableModel that extends AbstractTableModel..

Please help, I want the Jtable to refresh automatically when a change occur to its data in the database.
Martin Vajsar

Joined: Aug 22, 2010
Posts: 3733

AbstractTableModel doesn't have any built in support to monitor for database changes. I'm actually not aware of any JDK class that would support this out of the box.

When a database changes, you need to reflect the changes in the table model. Given that you're using AbstractTableModel, you'd be responsible for firing the proper table change events yourself. The easiest solution is to simply reload all data from the database and fire some global table change event (either fireTableDataChanged or fireTableStructureChanged).

If the table is based on a lots of data, reloading all of it can be costly. If you could detect what part of the table changed and reload only those data, you could save that work, and you could even fire some other table change event that would specify which cells or rows were updated or whether rows were inserted or deleted. Conceptually this is not complicated, but implementing such scheme gets quite laborious pretty fast (and remember to handle cell coordinate translation correctly if you use column reordering, or JTable filters or sorters). So my advice would be to implement just a full reload first.

The really hard part is to detect database changes. Generic JDBC doesn't support anything like this. Some databases (and their JDBC drivers) support specific mechanisms for alerting an application about changes to database tables (such as Database Change Notification in Oracle 10g an later), but these are of course database specific and can entail some limitations. A most generic solution would therefore be to constantly load all data from the database to see whether anything changed (this approach is sometimes called "polling", the application "polls" for changes). Depending on the nature of the data and interval between individual polls this could put considerable strain on the database, though.
I agree. Here's the link:
subject: JTable not refreshing
It's not a secret anymore!