I am adding a listener to the JCheckBox present in the JTable. I am having a issue with following code,
public class CheckBoxEditor extends DefaultCellEditor implements ItemListener {
private static final long serialVersionUID = 1L;
private JCheckBox checkBox;
private int row;
private int column;
public CheckBoxEditor(JCheckBox checkBox) {
super(checkBox);
this.checkBox = checkBox;
this.checkBox.addItemListener(this);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
this.row = row;
this.column = column;
checkBox.setSelected((Boolean) value);
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
public void itemStateChanged(ItemEvent e) {
this.fireEditingStopped();
System.out.println("Item Changed " + row + " value is: " + checkBox.isSelected());
}
}
and in I am using above class as,
tableA.getColumnModel().getColumn(4).setCellEditor(new CheckBoxEditor(new JCheckBox()));
When ever I click on the check boxes in the column I am reaching the itemStateChanged method. The problem is, on selection of a check box my itemStateChanged method is calling twice and some times only once.
This is the sample output. (I had 5 rows. And when I am making true all the check boxes I am getting this double syso printings.)
Item Changed 0 value is: true
Item Changed 1 value is: false
Item Changed 1 value is: true
Item Changed 2 value is: false
Item Changed 2 value is: true
Item Changed 3 value is: false
Item Changed 3 value is: true
Item Changed 4 value is: false
Item Changed 4 value is: true
Your listener is triggered when you click on the checkboxes, but also when the selected state is changed trough the API.
And since the editor always reuses the same checkbox it is constantly updating the selected value.
Main question is ... why would you need to attach a listener to it ?