I have a JXTable
compound of 6 columns and two of them are JCheckBox
. I would like to have the following behavior:
- If the first checkbox is checked, the second checkbox is enabled and can be checked or not.
- If the first checkbox is unchecked, the second must be disabled and unchecked.
I edited an image with Photoshop to show the desired result:
For the CheckOne
and CheckTwo
columns i use a custom TableCellEditor
and TableCellRenderer
:
public class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = 1L;
private JCheckBox checkBox = new JCheckBox();
public CheckBoxCellEditor() {
checkBox.setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
checkBox.setSelected(value==null ? false : (boolean)value);
return checkBox;
}
@Override
public Object getCellEditorValue() {
return checkBox.isSelected();
}
}
public class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer{
private static final long serialVersionUID = 1L;
public CheckBoxCellRenderer() {
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
setSelected(value==null ? false : (boolean)value);
return this;
}
}
And this is how i set them:
//CheckOne
table.getColumn(4).setCellEditor(new CheckBoxCellEditor());
table.getColumn(4).setCellRenderer(new CheckBoxCellRenderer());
//CheckTwo
table.getColumn(5).setCellEditor(new CheckBoxCellEditor());
table.getColumn(5).setCellRenderer(new CheckBoxCellRenderer());
I tried to add a PropertyChangeListener
to the JXTable
and implement the behavior from there, but i couldn´t get it done.
Then i realised that my custom editor and renderer were changing all the column components at the same time instead of only the desired component.
So, i tried to make the changes in the TableCellEditor
and TableCellRenderer
, and in the PropertyChangeListener
but, again, i couldn´t figure it out.
First off please note your problem is not related to JXTable but renderers / editors / model.
As @mKorbel points out JCheckBox is the default Renderer/Editor for booleans and generally speaking you won't need to re-invent the wheel: just override getColumnClass() properly to return Boolean on both 5th and 6th columns.
However, because of this requirement:
This is not the default renderer's behavior so you actually need your own renderer. But only renderer, you don't need an editor: as @mKorbel points out you need a little work with the table model.
Renderer
Model
You need to work on both isCellEditable() and setValueAt() methods to properly update your second booleans column based on values on first one. For instance consider this snippet:
Test it
Here is a complete test case. Hope it helps.