开发者

Initializing JCheckBoxes when they are generated by a Table Model

开发者 https://www.devze.com 2022-12-18 13:03 出处:网络
In Java Swing I have created a JTable which uses a table model class which extends Default开发者_运维问答TableModel. As the values of one row of the table are of boolean type, these are displayed as c

In Java Swing I have created a JTable which uses a table model class which extends Default开发者_运维问答TableModel. As the values of one row of the table are of boolean type, these are displayed as check-boxes. As I want to add to these check-boxes 'item listeners' classes, I do need to initialize each of these check-boxes. But how do I do if these are automatically created by the table model?


As these CheckBoxes change the underlying data, it should be sufficient to add a TableModelListener and react to tableChanged events of that column.

jTable1.getModel().addTableModelListener(new TableModelListener() {
    final int YOUR_BOOLEAN_COLUMN = 1;
    public void tableChanged(TableModelEvent e) {
        if(e.getColumn() == YOUR_BOOLEAN_COLUMN) {
            // get value from model (not affected if user re-orders columns)
            TableModel tableModel = jTable1.getModel();
            Boolean value =
                (Boolean)tableModel.getValueAt(e.getFirstRow(), YOUR_BOOLEAN_COLUMN);
            System.out.println(value);
        }
    }
});


The short answer is you can't add ActionListeners to the JCheckboxes in the table for two reasons:

  1. With the default setup, a single JCheckbox is used to render all checkbox cells.
  2. Mouse clicks on the table cell containing the JCheckBox are not passed on to the checkbox, they are absorbed by the table.

I think it's important to ask why you need these events? The answer you give will reflect the best approach to take.

If you want to allow the user to edit the state of the checkboxes, your best approach may be to override TableModel.isCellEditable(int, int) to return true for the Checkbox columns and then simply update original data as the TableModel is updated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号