Search code examples
javaswinglistenerjcheckboxtablemodel

Initializing JCheckBoxes when they are generated by a Table Model


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?


Solution

  • 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);
            }
        }
    });