Issue
I use Netbeans 8.2. I'm trying to get data from the database and display it in a jTable. But, when I run the program, I get the last row only.
Can anyone help me solve it?
public class MultiSpanCellTableExample extends JFrame {
Statement st;
ResultSet rs;
Object [][]row;
Object[] column;
MultiSpanCellTableExample() {
column = new Object[]{"","","","",""};
String g="",h="",j="",z="",n="",hg="",oo="",zz="";
Double l=null;
Date i=null;
String sql="SELECT * from personn";
con=Connections.getConnection();
try{
st=con.createStatement();
rs=st.executeQuery(sql);
while(rs.next()){
g=rs.getString("NAMME");
l=rs.getDouble("TOTAL");
i=rs.getDate("DATEE");
z=rs.getString("WY");
n=rs.getString("BAA");
row=new Object[][]{{g,l,z,i,n}};
}
}
catch(Exception e){
System.out.print( e);
}
AttributiveCellTableModel ml = new AttributiveCellTableModel(row,column);
final CellSpan cellAtt =(CellSpan)ml.getCellAttribute();
final MultiSpanCellTable table = new MultiSpanCellTable(ml);
JScrollPane scroll = new JScrollPane( table );
Box box = new Box(BoxLayout.X_AXIS);
box.add(scroll);
box.add(new JSeparator(SwingConstants.HORIZONTAL));
box.add(p_buttons);
getContentPane().add( box );
setSize( 400, 200 );
setVisible(true);
}
public static void main(String[] args) {
MultiSpanCellTableExample frame = new MultiSpanCellTableExample();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit(0);
}
});
}
}
Solution
Problem
You have not initialized row[][]
with the required number of rows. Moreover, you are not storing the records into row[i]
, where i
is the index. Note that a 2-D array is an array of arrays and therefore each record from the database represent a 1-D array which needs to be stored into row[i]
.
Solution
try{
// Get the number of rows
Statment stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rsCount = stmt.executeQuery("SELECT count(*) from personn");
if(rsCount.next()) {
// Initialize row[][]
row = new Object[rsCount.getInt(1)][];
st = con.createStatement();
rs = st.executeQuery(sql);
for(int i = 0; rs.next(); i++) {
g = rs.getString("NAMME");
l = rs.getDouble("TOTAL");
i = rs.getDate("DATEE");
z = rs.getString("WY");
n = rs.getString("BAA");
// Store the record into row[i]
row[i] = new Object[]{g,l,z,i,n};
}
}
}
Answered By - Arvind Kumar Avinash
Answer Checked By - Cary Denson (JavaFixing Admin)