Friday, September 15, 2006

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.

7 comments:

Anonymous said...

It's pretty simple really, just fire a table changed event.
It's easy to do if you extend AbstractTableModel.

or you can call
jtable.tableChanged(new TableModelEvent(jtable.getModel()))

Blackfoot said...

Thanks. My scenario was a bit more complex as the jTable was not actually getting changed, it was the underlaying database. So what I did was basically what you recommended except whenever I called my insert statement I grab the tableModel again which results in refreshing the data.

Anonymous said...

It sounds like you may want to add a TableModelListener, that looks for your insert event it, can then query your database for the updated data, and fire a tableChanged event.

You just have to be careful that you don't run your queries on the EDT, or your responsiveness will suck.

Anonymous said...

try this :
SwingUtilities.updateComponentTreeUI(yourJScrollPane);
this is from a french forums

Anonymous said...

use the repaint methods
ex:table.repaint()
use all the component

Pollo said...

I have found a solution for the refresh problem:


public class MyComponent implements Runnable{

....

// Component refresh method
public void refresh(){
SwingUtilities.invokeLater(this);
}

....

public void run(){
updateUI();
}

Anonymous said...

this here a solution. thanks
tableTemp.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);