防止复选框移入JTable

时间:2011-10-18 17:45:57

标签: java swing jtable jcheckbox

我在JTable中有一个列,其中的单元格呈现为下面的复选框:

enter image description here

如何在每次点击复选框时阻止复选框移动?这是我的单元格渲染器和单元格编辑器:

protected class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer {

  @Override
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    this.setSelected((Boolean) tableModel.getValueAt(row, 0));
    return this;
  }

}

protected class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {

  private final CheckBoxCellRenderer cell = new CheckBoxCellRenderer();
  private int row;

  public CheckBoxCellEditor() {
    cell.addActionListener(this);
  }

  @Override
  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
    cell.setSelected(((Boolean) value).booleanValue());
    row = rowIndex;
    return cell;
  }

  @Override
  public Object getCellEditorValue() {
    return cell.isSelected();
  }

}

谢谢!

1 个答案:

答案 0 :(得分:4)

不要创建自定义渲染器/编辑器。

JTable已经支持默认渲染器。只需覆盖TableModel或JTable的getColumnClass(...)方法,返回第一列的Boolean.class,JTable将使用默认的渲染器/编辑器。