问题
I'm trying to display all the records from my database table into an JTable. The problem is when I run the code it will only display the last record from the table.
Code:
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);
}
Isn't object[][] data supposed to show all the records from my table? And not only the last one.
回答1:
Isn't object[][] data supposed to show all the records from my table? And not only the last one
Yes, but you create a new 2D array and a new JTable for every row in the 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.
So the basic structure is:
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
while (rs.next())
{
....
model.addRow(...);
}
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
...
来源:https://stackoverflow.com/questions/44287646/jtable-only-displays-last-record-from-table