表格标题中的Jcheckbox给出了例外情况

时间:2018-07-01 03:09:26

标签: java swing jtable jcheckbox

我创建了一个JTable。有一个带有复选框的名为"Export"的列标题。当我们选择标题的复选框时,还应选中所有行中的复选框。

这是我的代码:

private void initializeTable() {
    tableModel = (DefaultTableModel) locationJTable.getModel();

    locationJTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    tableModelListener = new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            processTableChange(e);
        }
    };
    locationJTable.getModel().addTableModelListener(tableModelListener);

    tableSelectionListener = new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            //processSelection(e);
        }
    };
    locationJTable.getSelectionModel().addListSelectionListener(tableSelectionListener);

    Map<String, TableColumn> columns = new HashMap<String, TableColumn>() {
        {
            put("Export", locationJTable.getColumnModel().getColumn(INDEX_OF_THE_EXPORT_COLUMN));
        }
    };

    for (Map.Entry<String, TableColumn> entry : columns.entrySet()) {
        TableColumn column = entry.getValue();
        ItemListener itemListener = (ItemEvent e)
                -> {
            Object source = e.getSource();
            if (source instanceof AbstractButton == false) {
                return;
            }

            boolean checked = e.getStateChange() == ItemEvent.SELECTED;
            for (int x1 = 0, y1 = locationJTable.getRowCount(); x1 < y1; x1++) {
                **if ((boolean) locationJTable.getValueAt(x1, column.getModelIndex()) != checked)** {
                    locationJTable.setValueAt(checked, x1, column.getModelIndex());
                }
            }
        };

        boolean selected = true;
        if (entry.getKey().equals("Export")) {
            selected = false;
        }

        CheckBoxHeader header = new CheckBoxHeader(itemListener, selected, entry.getKey(), column.getModelIndex());
        locationJTable.getTableHeader().setBackground(new Color(255, 255, 255));
        column.setHeaderRenderer(header);
        checkBoxHeaders.put(header, itemListener);
    }
}

我在构造函数中调用此函数。当我勾选标题中的复选框而不是选中其他复选框时,它显示了NullPointerException。但是,如果我先在一行中选中复选框,然后再选中标题复选框,它就会按预期检查表行中的所有其他复选框。发生异常时进行调试时,locationJTable.getValueAt(x1, column.getModelIndex()显示null

为什么?

0 个答案:

没有答案