添加到 JTable 中的特定单元格会抛出 java.lang.ArrayIndexOutOfBoundsException: 4 >= 0

adding to a specific cell in JTable is throwing java.lang.ArrayIndexOutOfBoundsException: 4 >= 0

java.lang.ArrayIndexOutOfBoundsException: 4 >= 0 异常

我创建了一个方法来将对象添加到 JTable 中的特定单元格 它抛出了 java.lang.ArrayIndexOutOfBoundsException: 4 >= 0 异常

这些是我的部分代码

    //creating a JTable and a table model
    horaireTable = new JTable();
    modelHT = new DefaultTableModel();
    modelHT.setColumnIdentifiers(rowHead);
    horaireTable.setModel(modelHT);
    horaireTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    horaireTable.getColumnModel().getColumn(0).setMinWidth(106);
    horaireTable.getColumnModel().getColumn(1).setMinWidth(107);
    horaireTable.getColumnModel().getColumn(2).setMinWidth(106);
    horaireTable.getColumnModel().getColumn(3).setMinWidth(107);
    horaireTable.getColumnModel().getColumn(4).setMinWidth(106);
    horaireTable.getColumnModel().getColumn(5).setMinWidth(107);
    horaireTable.getColumnModel().getColumn(6).setMinWidth(106);

    JScrollPane paneHT = new JScrollPane(horaireTable);

    paneHT.setPreferredSize(new Dimension(750, 130));

    //getting data to add
    int j,s;

    j = listJours.getSelectedIndex();  //listJours and listSeance are two 
    s = listSeance.getSelectedIndex(); // Jlists containing strings
    String h ="exemple";

    //adding to the table
    modelHT.setValueAt(h,s,j);

我得到的结果是 java.lang.ArrayIndexOutOfBoundsException: 4 >= 0 异常

the result I get is a java.lang.ArrayIndexOutOfBoundsException: 4 >= 0 exception

您正在尝试更新 TableModel 中不存在的单元格。

modelHT = new DefaultTableModel();

您创建了一个包含 0 行和 0 列的空 TableModel。

modelHT.setColumnIdentifiers(rowHead);

然后您将 7 列 headers 添加到 table 但您仍然有 0 行数据。

modelHT.setValueAt(h,s,j);

如果模型中不存在单元格,则不能只设置单元格的值。

如果要更改单元格中的数据,则该数据必须存在于 TableModel 中。

一种方法是创建一个具有定义的行数和列数的 TableModel:

//modelHT = new DefaultTableModel();
modelHT = new DefaultTableModel(rowHead, 5); 

这将创建一个模型,其中包含您的 "rowHead" 变量指定的列数和每个单元格中包含空值的 5 行数据。

另一种方法是首先创建一个只定义列的 TableModel,然后根据需要动态添加数据行:

modelHT = new DefaultTableModel(rowHead, 0); 
...
modelHT.addRow(...);