javacheckboxgwtonclickgwt-celltable

Check/Uncheck CheckboxCell, onclick of a row - GWT


I have a cell table with the first column as checkboxes. My checkboxes have to be checked or unchecked when there is any single click event on the entire row. This is the following code for creating a MultiSelectionModel, creating CheckboxCell and creating a column for cell table.

MultiSelectionModel<Object> selectionModel = new MultiSelectionModel<>();
    table.setSelectionModel(selectionModel);

    CheckboxCell selectedCell = new CheckboxCell();
    Column<Object,Boolean> selectedCol = new Column<Object, Boolean>(selectedCell){
        @Override
        public Boolean getValue(Object object) {
            return object.isSelected();
        }
    };
    table.addColumn(selectedCol);


    //Single Click Event to Enable/Disable checkbox.
    table.addDomHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            Set<Object> selectedItems = selectionModel.getSelectedSet();

            for (Object s : selectedItems) {
                Window.alert(String.valueOf(s));
                selectionModel.setSelected(s, true);
            }
        }
    }, ClickEvent.getType());

I tried to mark a row as checked using "selectionModel.setSelected(s, true)". But it isn’t working, when I clicked on row, the corresponding checkbox is not being checked.

My question is how do I enable/disable checkboxes onclick of an entire row. Is my approach correct. Or Is there any other way to perform this action in GWT.


Solution

  • You are very close to the working solution.

    In the selectedCell you should return the value depending on selectionModel:

    return selectionModel.isSelected(object);
    

    This way you are using default multi selection model that selects rows by clicking on them. And the checkbox value comes from the selection model. That's it.

    See the working example below:

    CellTable<String> table = new CellTable<String>();
    
    final MultiSelectionModel<String> selectionModel = new MultiSelectionModel<>();
    table.setSelectionModel(selectionModel);
    
    CheckboxCell selectedCell = new CheckboxCell();
    Column<String, Boolean> selectedCol = new Column<String, Boolean>(selectedCell) {
        @Override
        public Boolean getValue(String object) {
            // return object.isSelected();
            return selectionModel.isSelected(object);
        }
    };
    table.addColumn(selectedCol);
    
    table.addColumn(new TextColumn<String>() {
        @Override
        public String getValue(String object) {
            return object;
        }
    });
    
    List<String> values = new ArrayList<>();
    for(int i = 0; i < 10; i++)
        values.add("Line " + (i + 1));
    table.setRowData(values);
    

    You can use standard Ctrl and Shift keys to control selection.

    enter image description here