JTable - Checkbox add action listener

回眸只為那壹抹淺笑 提交于 2020-05-27 11:49:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/22710570/jtable-checkbox-add-action-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!