I followed the directions somewhere online to insert checkboxes in a JTable. Here is my code to do so:
protected class JTableCellRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JCheckBox rendererComponent = new JCheckBox();
rendererComponent.setSelected((Boolean) tableModel.getValueAt(row,
column));
return rendererComponent;
}
}
I managed to add checkboxes to a JTable, but then when I run my program, I get the following behavior:
How do I allow a user to check the checkbox instead of selecting True or False from the dropdown menu when he or she clicks on the checkbox? Thanks!
The directions you are following are bad as there's no need to fiddle with renderers or editors (and by the way, your problem is that you changed the renderer without changing the editor). All you have to do is in your TableModel class, override the getColumnClass(int index)
method and have it return Boolean.class for the column that needs check boxes. That's it. The JTable will automatically use a checkbox both for the column's renderer and editor solving your problem in a very easy way. Of course it should go without saying that the data for that column must be Boolean for this to work.
The Oracle tutorial on JTables will tell you all this and more: How to use Tables