Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable - Checkbox add action listener

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.

like image 772
chinna_82 Avatar asked Dec 19 '22 16:12

chinna_82


1 Answers

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:

  • Add a new TableModelListener to your TableModel
  • Validate if the updated cell value is a Boolean and its value is true.
  • Ask the user to confirm the update. If s/he doesn't then set the cell's value back to false.
  • See TableModelEvent API as well.

Edit

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.

like image 169
dic19 Avatar answered Dec 22 '22 04:12

dic19