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.

9 comments:

Anonymous said...

Hi,

two questions... How are you using MVC architecture? and what happens if your INSERT statement fails?

Sorry, but I can't figure it out without a code snippet.

Regards,
Pablo.

Blackfoot said...

Hi Pablo,
I've tried to use the TableModel to handle the data components (as my app is based on a single outside table.) I use a builder PanelBuilder to handle my View and the placement of all components of my form. The area that is still a bit mushed together is the Control as I have a "Save" button which has the INSERT code on an Action Listener and this still violates a pure MVC architecture. Any recommendations for how better to structure this?
Currently if my INSERT statement fails I catch it with an exception.

Anonymous said...

If you fire TableChanged events from your model, you shouldn't need to .revalidate your JTable.
I never call revalidate, and My tables update all the time.
I put a JProgessBar in a cell and have it fireTableCellUpdated every 250ms, so that it draws the bar going accross.

Blackfoot said...

Thanks, I am going to try this.

Anonymous said...

It was rather interesting for me to read the blog. Thanx for it. I like such topics and anything that is connected to this matter. I would like to read a bit more on that blog soon.

Anonymous said...

Keep on posting such stories. I like to read blogs like this. BTW add some pics :)

Anonymous said...

Great story you got here. I'd like to read something more concerning that theme. The only thing I would like to see on that blog is some photos of some gadgets.
Alex Trider
Cell phone blocker

Anonymous said...

You commit an error. Write to me in PM.

Anonymous said...

How can i put hour long music podcast onto 80min cds,TIA.

Well i would suggest that you re-encode the podcast to a lower bit-rate to fit on the CD depending on the size of the podcast
[url=http://www.topvideoconverter.com/aac-converter/]convert mp3 to aac[/url]