setValueAt 用于 JTable Multiarray 中的复选框值

setValueAt for check box value in JTable Multiarray

我目前在为 JTable 中的 Checkbox 设置值时遇到问题。 我需要在 table 的行中为每个复选框存储布尔值。 我可以显示 default(false) 复选框,但是一旦我点击复选框,我就会得到一个异常; java.lang.ArrayIndexOutOfBoundsException:0。 我不太熟悉带有布尔值的多数组,我似乎无法弄清楚我的代码的哪一部分不正确。

public static final int CHECKBOX= 0;
private final List<Data> datas;
private static boolean CHECKBOX_RENDERED[][] = new boolean[][]{};
private static Arrays array = null;

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    if (rowIndex >= this.datas.size()) {
        return null;
    }

    Data theData= this.datas.get(rowIndex);
    if (theData== null) {
        return null;
    }

    //Initialize the boolean field with table dimension
    CHECKBOX_RENDERED = new boolean[datas.size()][columnIndex];

    switch(columnIndex) {
    case CHECKBOX:
        array.fill(CHECKBOX_RENDERED[rowIndex], false);
        return false; //default
    default:
        throw new IllegalArgumentException("Invalid column index");
    }
}


@Override
public void setValueAt(Object value, int row, int column) {
    if (column == CHECKBOX) {
        Data data= this.datas.get(row);
        if (data!= null && value instanceof Boolean) {

            if (CHECKBOX_RENDERED[row][column]) {
                CHECKBOX_RENDERED[row][column] = false;
            } else {
                CHECKBOX_RENDERED[row][column] = true;
            }

            fireTableCellUpdated(row, column);
        }
    }
}
private static boolean CHECKBOX_RENDERED[][] = new boolean[][]{};

您定义了一个二维数组变量,但实际上从未定义数组的行和列的大小。因此,数组的大小为 (0, 0),您不能 add/change 数组中的任何数据。

不要创建您自己的 table 模型。

最简单的解决方案是只使用 DefaultTableModel。它将为您管理数据。您只需要在 table 中定义您想要的 rows/columns 的数量,它将为您管理其余的。

或者,如果您不知道需要多少行数据,那么您可以使用 addRows(...) 方法根据需要动态添加行。