且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JTable仅显示表中的最后一条记录

更新时间:2021-09-13 04:36:39

object [] []数据不是应该显示表中的所有记录吗?而且不仅是最后一个

Isn't object[][] data supposed to show all the records from my table? And not only the last one

是的,但是您要为ResultSet中的每一行创建一个新的2D数组和一个新的JTable.

Yes, but you create a new 2D array and a new JTable for every row in the ResultSet.

相反,您需要在循环开始之前创建一个空的DefaultTableModel,然后在循环内使用addRow(...)方法将ResultSet中的数据行添加到表模型中.

Instead you need to create an empty DefaultTableModel before the loop starts, Then inside the loop you use the addRow(...) method to add the row of data from the ResultSet to the table model.

然后,当循环结束时,您将使用表模型创建表.

Then when the loop is finished, you create the table using the table model.

所以基本结构是:

DefaultTableModel model = new DefaultTableModel(columnNames, 0);

while (rs.next())
{
    ....
    model.addRow(...);
}

JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
...