Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help with TableModel code I've got...  RSS feed

 
Cory Lutton
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the code......

import java.sql.*;
import javax.swing.table.AbstractTableModel;
import java.util.*;

public class BOMModel extends AbstractTableModel {

ResultSet rs;
ArrayList cache = new ArrayList();

public BOMModel(ResultSet rs){
this.rs = rs;
this.initCache();
}

public int getColumnCount() {
return 2;
}

public int getRowCount() {
if(rs == null)
return 0;
else
return cache.size();
}

public Object getValueAt(int row, int col) {
try{
if(row < cache.size())
return ((Object[])cache.get(row))[col];
else
return null;
}
catch(Exception e){
e.printStackTrace(System.out);
return null;
}
}
/*
* Breakdown resultset to vector for use in getRowCount, and getValueAt
*/
private void initCache(){
if(rs != null){
try{
Object[] row = new Object[2];
while(this.rs.next()){
row[0] = rs.getString(9);
row[1] = rs.getString(12);
cache.add(row);
}
}
catch(SQLException se){
se.printStackTrace(System.out);
}
}
}
}


It seems to work for creating the table however the records are all the last result from the query (there are 17 rows all the same). I think I am missing something probably in the initCache or getValueAt code. It is probably something simple, am new to this so please be gentle.

Thanks
 
Eddie Vanda
Ranch Hand
Posts: 283
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I don't think this is the problems, but you probably should refer to "rs" either with or without "this" in all three references to rs. What you say might be consistent with the "next" referring to one result set and "getString" to another, but I cannot see any other "rs" objects in your code so I may be giving you a red herring!
 
Catalin Merfu
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Allocate a new Object array for each tuple.

Replace this:
...
Object[] row = new Object[2];
while(this.rs.next()){
row[0] = rs.getString(9);
row[1] = rs.getString(12);
cache.add(row);
}
...
with this:
...
while(this.rs.next()){
Object[] row = new Object[2];
row[0] = rs.getString(9);
row[1] = rs.getString(12);
cache.add(row);
}
...

You'll figure out by yourself what was wrong.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!