views:

73

answers:

2

In Java Swing I have created a JTable which uses a table model class which extends DefaultTableModel. 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?

+2  A: 

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);
        }
    }
});
Peter Lang
+1  A: 

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.

Jason Nichols