【问题标题】:Listener for CheckBox in JTableJTable 中复选框的侦听器
【发布时间】:2012-10-30 14:37:02
【问题描述】:

我正在向 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 行。当我将所有复选框设置为 true 时,我得到了这个双 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

【问题讨论】:

  • 我认为您会使用添加到 JTable 模型中的 TableModelListener,而不是添加到行编辑器组件中的东西。
  • 感谢您的建议..让我试试这个..
  • @Che ItemListener 总是触发两次,必须确定是 SELECTED 还是 DESELECTED,然后建议

标签: java swing jtable jcheckbox itemlistener


【解决方案1】:

当您单击复选框时触发您的侦听器,而且当通过 API 更改选定状态时也会触发您的侦听器。

由于编辑器总是重复使用同一个复选框,它会不断更新选定的值。

主要问题是......为什么需要给它附加一个监听器?

【讨论】:

  • 我需要知道复选框何时被选中..基于此我需要调用与此更改关联的方法。如果这是错误的方式..你能告诉我比这更好的吗?
  • @Che 正如 Hovercraft 所建议的,你需要在模型中而不是在编辑器中监听变化
  • @Che 如果您想知道复选框何时被选中,请考虑使用ActionListener 而不是ItemListener
  • @GuillaumePolet 太棒了.. 它有效.. 但很想知道 JTable 的 ItemChnaged 和 ActionListener 有什么区别
猜你喜欢
  • 2011-06-30
  • 2015-10-20
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 2013-01-10
  • 2012-11-14
相关资源
最近更新 更多