Search code examples
javagwtgwt-celltable

GWT CellTable/DataGrid - how to detect column selection?


When a row is selected, I would like to know which column of that row was selected.

Currently, I would override onBrowserEvent2

protected void onBrowserEvent2(Event event)
{
  // Get the event target.
  EventTarget eventTarget = event.getEventTarget();
  if (!Element.is(eventTarget)){
    return;
  }

  final Element target = event.getEventTarget().cast();

  // Find the cell where the event occurred.
  TableCellElement tableCell = findNearestParentCell(target);
  if (tableCell == null) {
    return;
  }

  int col = tableCell.getCellIndex();

  .... blah ... blah ....
}

where,

//exact replica code from {@link AbstractCellTable} private method findNearestParentCell
private TableCellElement findNearestParentCell(Element elem) {
  while ((elem != null) && (elem != getElement())) {
    // TODO: We need is() implementations in all Element subclasses.
    // This would allow us to use TableCellElement.is() -- much cleaner.
    String tagName = elem.getTagName();
    if ("td".equalsIgnoreCase(tagName) || "th".equalsIgnoreCase(tagName)) {
      return elem.cast();
    }
    elem = elem.getParentElement();
  }
  return null;
}

Is this the only way? Is there a selection model with a change event that would tell me which column of the row was clicked.

Is there a way to implement a click handler on a column or the cell of the column?


Solution

  • OMG ... this was a really simple solution.

    Use an extension of ClickableTextCell for the column.

    public class SelectableTextCell
    extends ClickableTextCell
    {
      @Override
      public void onBrowserEvent(
        Context context,
        Element parent,
        String value,
        NativeEvent event,
        ValueUpdater<String> valueUpdater)
      {
        GWT.log("event="+event.getType()); //$NON-NLS-1$
        doYourThing();
        if (IWishToPropagateTheClick)
          super.onBrowserEvent(context, parent, value, event, valueUpdater);
      }
    }
    

    Or for a more general case, extend AbstractCell, and specify the consumed events at the constructor.