Make only one checkbox selectable in JTable column
I have a JTable with 2 coloumns, one column is the object type, the second column is a checkbox. In this table, the user only wants to select one checkbox. I tried many codes (Examples: jtable checkbox single selection and Second ), finally I did it using a function.
Here is my function:
public void setSelectionEnableOrDisable(JTable table) {
int earlierSelectionRow = 0;
int selectedRow = table.getSelectedRow();
for (int i = 0; i < table.getRowCount(); i++) {
if ((Boolean) table.getValueAt(i, 1) == true && i != selectedRow) {
earlierSelectionRow = i;
}
}
table.setValueAt(true, selectedRow, 1);
table.setValueAt(true, earlierSelectionRow, 1);
}
But, what's the problem with this, when I click on the checbox slowly, it's good. if I quickly click 2 or 3 checkboxes then my code allows multiple selections. What's wrong here?
+3
source to share
1 answer
I think you can make it easier, for example:
public void setSelectionEnableOrDisable(JTable table) {
int selectedRow = table.getSelectedRow();
if ((Boolean)table.getValueAt(selectedRow , 1)) {
for (int i = 0; i < table.getRowCount(); i++) {
if ( i != selectedRow) {
table.setValueAt(false, i, 1);
}
}
}
+1
source to share