I've created a simple JTable
with check box like below:
DefaultTableModel model = new DefaultTableModel();
jTable1.setModel(model);
model.addColumn("No:", no1);
model.addColumn("Remark", remark1);
model.addColumn("Color", colors1);
model.addColumn("Done");
TableColumn col1 = jTable1.getColumnModel().getColumn(0);
col1.setPreferredWidth(1);
TableColumn col4 = jTable1.getColumnModel().getColumn(3);
col4.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col4.setCellRenderer(jTable1.getDefaultRenderer(Boolean.class));
col4.setPreferredWidth(50);
jTable1.setShowGrid(true);
jTable1.setGridColor(Color.BLACK);
jTable1.setAutoCreateRowSorter(true);
It's working fine but how to do if I want to add action listener for the check box. For an example, when my check box is checked I need to pop up a confirmation message.
For an example, when my check box is checked I need to pop up a confirmation message.
You don't need to add an ActionListener to the renderers/editors but you need to listen to table model data changes. Take a look to Listening for Data Changes section of How to Use Tables tutorial:
Boolean
and its value is true
.false
.Note in this case as you're working with booleans then there's 2 possible values to do the check. However for input validation in other cases the described procedure won't work simply because the listener will be notified when the change already happened and you won't be able to set the value back just because it won't be there any longer.
Take a look to @kleopatra's answer to this question: JTable Input Verifier. As stated there a better approach is providing a custom CellEditor and do the validation in stopCellEditing() method implementation. Just as a suggestion I'd use a DefaultCellEditor that takes a JCheckBox as parameter and override the aforementioned method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With