在DefaultCellEditor派生实例执行其工作后更新单元格渲染器

时间:2009-05-27 17:47:11

标签: java swing jtable

我使用JTable,它有自己的单元格渲染器和单元格编辑器。

说,这个表包含2列和x行:
第一列包含一个布尔值,它自己的单元格渲染和单元格编辑器(一个单选按钮)
第二列包含一个字符串值,它自己的单元格渲染器:当当前行的第一列设置为true(检查radiobutton)时,它使其变为粗体

编辑器正确更新了所有值,但当单选按钮设置为true时,第2行不会变为粗体...
我必须检查另一行的单选按钮才能看到更改

我可以在哪里解雇变化?

干杯并感谢您的帮助


RadiobuttonTableCellEditor.java

public class RadiobuttonTableCellEditor extends DefaultCellEditor
                                    implements ItemListener {
JRadioButton rb = new JRadioButton();

public RadiobuttonTableCellEditor(JCheckBox pCheckBox) {
    super(pCheckBox);
}

public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    if (value == null)
        return null;
    rb.addItemListener(this);
    rb.setSelected((Boolean)value);
    return rb;
}

public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
}

public Object getCellEditorValue() {
    rb.removeItemListener(this);
    return rb.isSelected();
}
}

3 个答案:

答案 0 :(得分:1)

在您的表模型中,只要您的值发生变化,您就必须触发相应的事件。如果您的模型继承自AbstractTableModel,则可以使用多种fireXXX方法。我的猜测是你应该用setValueAt方法调用它们。

如果您知道确切的列和行 - 您可以致电fireTableCellUpdated,否则您可能必须使用fireTableChanged,因为您必须更新不同的列。

当然,渲染器应该正确渲染新值。

答案 1 :(得分:0)

DeafultCellEditor扩展到那里似乎没有任何意义。实现这样的监听器界面也不是一个好主意。

渲染器最适合作为薄层使用。如果另一个单元格应该更改,则需要在表模型中反映出来,该模型应该触发相关的更新事件。

答案 2 :(得分:0)

我想它可以帮助有类似问题的人,让true单片机连续排成一行,你必须扩展DefaultTableModel来修改它的行为,尤其是setValueAt方法

干杯


/**
 * When <code>column</code> is the column that contains the Boolean (in fact the radio button):
 * If aValue == false and that it had a previous value set to true we don't do anything
 * If aValue == true and that it had a previous value set to false, we set all the other booleans to false and this one to true
 */
@Override
public void setValueAt(Object aValue, int row, int column) {
    if (column == colonneBoutonradio)
    {
        if (((Boolean)aValue && !(Boolean)super.getValueAt(row, column)))
            for (int i = 0; i < this.getRowCount(); i++)
                // i==row permet de vérifier si la ligne courante est celle à modifier (et donc celle à mettre à true)
                super.setValueAt(i==row, i, colonneBoutonradio);
    }
    else
        super.setValueAt(aValue, row, column);
}