我正在尝试将数据库表中的所有记录显示到 JTable 中。问题是当我运行代码时,它只会显示表中的最后一条记录。
代码:
public uitgifteInfo() throws SQLException{
final JFrame frame = new JFrame("Uitgifte punten");
String[] columns = {"Nummer", "Adres", "Postcode", "Plaats",
"capaciteit"};
String sql = "SELECT * FROM uitgiftepunt";
try (
Connection conn = connection.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
){
while (rs.next()) {
int nummer = rs.getObject("nummer", Integer.class);
String adres = rs.getObject("adres", String.class);
String postcode = rs.getObject("postcode", String.class);
String plaats = rs.getObject("plaats", String.class);
int cap = rs.getObject("capaciteit", Integer.class);
Object[][] data = {
{nummer,adres,postcode,plaats,cap}
};
JTable table = new JTable(data, columns);
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
JLabel lblHeading = new JLabel("Uitgiftepunt Info");
lblHeading.setFont(new Font("Arial",Font.TRUETYPE_FONT,24));
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(lblHeading,BorderLayout.PAGE_START);
frame.getContentPane().add(scrollPane,BorderLayout.CENTER);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(550, 550);
frame.setVisible(true);
}
难道 object[][] 数据不应该显示我表中的所有记录吗?不仅是最后一个。
最佳答案
Isn't object[][] data supposed to show all the records from my table? And not only the last one
是的,但是您为 ResultSet 中的每一行创建了一个新的二维数组和一个新的 JTable。
相反,您需要在循环开始前创建一个空的 DefaultTableModel,然后在循环内使用 addRow(...)
方法将 ResultSet 中的数据行添加到表模型.
然后当循环完成时,您使用表模型创建表。
所以基本结构是:
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
while (rs.next())
{
....
model.addRow(...);
}
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
...
关于java - JTable 只显示表中的最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44287646/