3

I have a JTable with 2 coloumns, one column is object type, second column is checkbox. In that table user want to select only a single checkbox. I am tried many codes (Examples : jtable checkbox single selection and Second one), finally i done this by using 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, whats the problem with this one is, when i clicking the checbox slowly it's fine. if i am clicking fastly 2 or 3 checkboxes then my code allows to multi selection. What's wrong here?.

Community
  • 1
  • 1
Thirunavukkarasu
  • 208
  • 6
  • 26
  • This has been answered previously with a very elegant example - http://stackoverflow.com/questions/7920068/using-setvalueat-to-recreate-mutually-exclusive-check-boxes/7920159#7920159 – ring bearer Jul 01 '15 at 13:42

1 Answers1

1

I think you can do it simpler, like:

 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);
    }
  }

}
sboda
  • 363
  • 4
  • 10