Ludmils
Ludmils

Reputation: 1

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 >= 0 defaultTableModel Java

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

Answers (1)

camickr
camickr

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:

  1. 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.

  2. 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:

  1. Don't use updateUI(). Swing components will auotmatically repaint themselves when the model is updated.

  2. Don't use a null layout. Swing was designed to be used with layout managers.

  3. Typically a JTable is used with a JScrollPane and the scroll pane is added to the frame.

Upvotes: 0

Related Questions