简体   繁体   中英

make only one checkbox selectable in JTable Column

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?.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM