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.