我正在向 JTable 中的 JCheckBox 添加一个侦听器。我对以下代码有疑问,
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());
}
}
在我使用上面的类时,
tableA.getColumnModel().getColumn(4).setCellEditor(new CheckBoxEditor(new JCheckBox()));
每当我单击列中的复选框时,我都会到达 itemStateChanged 方法。问题是,在选择复选框时,我的 itemStateChanged 方法调用了两次,有时只调用一次。
这是示例输出。(我有 5 行。当我把所有复选框都设置为真的时,我得到了这个双 syso 打印。)
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