3

I am using a SwingWorker to load data from a database into my JTable through a custom TableModel using the approach suggested here : How to fill data in a JTable with database? . If I bind my TableModel before I go on to process the ResultSet in the SwingWorker, I end up with an empty List inside the table model and JTable complains. If I bind the model after I have made a call to the SwingWorker , my JTable misses some of the callbacks that are fired by the publish method to update the rows in the table. Here is what my code looks like :

class MyTableModel{
 ResultSet rs;
 //Row is an intenral row object that is obtained after processing resultset  
 List<Row> data

 MyTableModel(){
 //initalise the row, rs etc;
 } 

 public void updateData(List<Row> r){
    data.addAll(r);
 }

 //called as a callback by another class that manages the queries
 public void processResults(ResultSet rs){
   new SwingWorker<Void,Row>(){
    doInBackground(){
     //process row by row
     publish(row);
    }
    public void process(List<Row> chunks){
       updateData(chunks);
       fireTableDataChanged();
    }
   }.execute();
 }

}

And this is how I am setting my table model right now

MyTableModel m = new MyTableModel();
//pass m as callback to the database manager which invokes processResults() on m
dbm.makeQuery("SELECT bit,pat from bot;",m);
table.setModel(m);
Community
  • 1
  • 1
adi
  • 580
  • 2
  • 12

1 Answers1

2

First, I (personally) wouldn't really use fireTableDataChanged() method for this purpose, it will require that the JTable completely repaint itself (including the columns). This is going to greatly increase the repaint times as the data set grows...

public void updateData(List<Row> r){
    int firstRow = getRowCount();
    data.addAll(r);
    int lastRow = getRowCount() - 1;

    fireTableRowsInserted(firstRow, lastRow);

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366