Reputation: 1
I would like to save and display data from database in JTable, and tried to use defaultTableModel for that. However, I'm getting:
ArrayIndexOutOfBoundsException at com.mycompany.bazadanych.main.main(main.java:40) (line with ** **).
Is there a method to predefine count of columns/rows in JTable and simply pass data to them?
public static void main(String[] args) {
bazaDanych BazaDanych = new bazaDanych();
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
tableModel.setColumnCount(3);
try {
//BazaDanych.wstawDane("STUDENCI", "Kowalski", "Jan");
//BazaDanych.wstawDane("STUDENCI", "Wiśniewski", "Piotr");
//BazaDanych.wstawDane("STUDENCI", "Nowak", "Michał");
BazaDanych.usunDane("STUDENCI", "Nowak", "Michał");
} catch (SQLException ex) {
ex.printStackTrace();
}
List<Student> lista = BazaDanych.pobierzDane("STUDENCI");
BazaDanych.zamknijPolaczenie();
lista.forEach(s -> {
**table.setValueAt(s.getId(), s.getId(), 0);**
table.setValueAt(s.getNazwisko(), s.getId(), 1);
table.setValueAt(s.getImie(), s.getId(), 2);
//tableModel.addRow(new Object[] {s.getId(), s.getNazwisko(), s.getImie()});
System.out.println(s.getId() + " " + s.getNazwisko() + " " + s.getImie());
});
table.updateUI();
//stable.setModel(tableModel);
JFrame frame = new JFrame("Demo program for JFrame");
frame.setLayout(null);
frame.add(table);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
}
}
Upvotes: -1
Views: 37
Reputation: 324187
Is there a method to predefine count of columns/rows in JTable and simply pass data to them?
How do you know what the predefined size of the table should be?
Your data is contained in a List of Students. The better approach would be to:
Create a custom StudentTableModel
. Then there is no need for the forEach loop. You just create the model using the List<Student>
. See Row Table Model for a step-by-step example on how to create a custom model.
Use the addRow(...)
method of the DefaultTableModel
as indicated in your code. This means you need to get rid of the setValueAt(...)
statements.
Other issues with the code:
Don't use updateUI(). Swing components will auotmatically repaint themselves when the model is updated.
Don't use a null layout. Swing was designed to be used with layout managers.
Typically a JTable is used with a JScrollPane and the scroll pane is added to the frame.
Upvotes: 0