java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 attempting to populate JTable

前端 未结 10 1598
猫巷女王i
猫巷女王i 2020-12-20 13:37

I\'m subclassing JTable and using a DefaultTableModel to model my table data. The following class sets up the JTable, and adds one row to the model.

import          


        
相关标签:
10条回答
  • 2020-12-20 14:33

    I ran on this issue too (with a JList and a DefaultListModel). Dmitry's answer is right.

    However, there is another thing: this exception can also be thrown if you don't modify the model in Swing's Event Dispatch Thread.

    Doing the following can help you avoid this exception:

    SwingUtilities.invokeLater(new Runnable(){public void run(){
        //Update the model here
    }});
    

    http://www.javakb.com/Uwe/Forum.aspx/java-gui/3012/JList-JScrollPane-DefaultListModel-Updating

    0 讨论(0)
  • 2020-12-20 14:35

    Another issue might be related when you use RowSorter. When you edit the model RowSorter tries to re-sort the old model. It should be automatically re-created and re-run on each changes of table model.

    You can fix it by

    tableModel = new DefaultTableModel(data, columnNames);
    jTableSentence.setModel(tableModel);
    jTableSentence.setRowSorter(new TableRowSorter(tableModel));
    jTableSentence.setAutoCreateRowSorter(true);
    

    -Hayri

    0 讨论(0)
  • 2020-12-20 14:38

    I was facing this problem because i was adding columns and rows to the JTable not to the model.

    best way is this.

    Object[][]rows = new Object[ ][ ] { {"a","b"} , {"c","d"} };
    Object[]columns = new Object[] {"column1","column2"};
    JTable table = new JTable();
    table.setModel(new DefaultTableModel(rows,columns));
    
    0 讨论(0)
  • 2020-12-20 14:38

    Dmitry is right, but you simply have to update your model. To do this, add the following to your code:

    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    for (int c = 0; c < table.getColumnCount(); c++) {
    dtm.addColumn(table.getColumnName(c));
    }
    
    0 讨论(0)
提交回复
热议问题