0

我编写了这个简单的代码来填充jTable1,但它只填充jTable1了数据库中的最后一行。

String SQL = "select * from usernames";
ResultSet rs = stmt.executeQuery(SQL);
String[] columnNames = {"Full Name", "Email"}; 
String n = "",e = "";
while(rs.next()) { 
    n = rs.getString("Full_Name");
    e = rs.getString("Email");
    Object[][]data = {{n,e}}; 
    jTable1 = new JTable(data, columnNames);

}       
4

2 回答 2

4

我通过这段代码解决了它

String n = "",e = "";      

DefaultTableModel model;
model = new DefaultTableModel(); 
jTable1 = new  JTable(model);

model.addColumn("Full Name");
model.addColumn("Email");

while(rs.next())  
{
    n = rs.getString("Full_Name");    
    e= rs.getString("Email");   
    model.addRow(new Object[]{n,e});
}
于 2012-08-27T19:07:32.043 回答
2

是的,它将始终是最后一行,因为在 while 循环中,您正在创建一个新的 JTable,而不是在现有的 JTable 中追加一行。所以这样做,

// Code
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
while(rs.next())
{ 
    n = rs.getString("Full_Name");
    e= rs.getString("Email");
    //Object[][]data={{n,e}};
    // This will add row from the DB as the last row in the JTable. 
    model.insertRow(jtable1.getRowCount(), new Object[] {n, e});
}       
于 2012-08-26T06:33:08.987 回答