Search code examples
javahtmlgwtmgwt

How to get List index of tapped List item?


I have a list of GWT three FlowPanels which contains two buttons each in ui binder:

<g:FlowPanel>

  <g:FlowPanel>
     <g:FocusPanel ui:field="buttonA1">...</g:FocusPanel>
     <g:FocusPanel ui:field="buttonB1">...</g:FocusPanel>
  </g:FlowPanel>

  <g:FlowPanel>
     <g:FocusPanel ui:field="buttonA2">...</g:FocusPanel>
     <g:FocusPanel ui:field="buttonB2">...</g:FocusPanel>
  </g:FlowPanel>

  <g:FlowPanel>
     <g:FocusPanel ui:field="buttonA3">...</g:FocusPanel>
     <g:FocusPanel ui:field="buttonB3">...</g:FocusPanel>
  </g:FlowPanel>

</g:FlowPanel>

ButtonA1,ButtonA2,ButtonA3 share a ClickHandler. ButtonB1,ButtonB2,ButtonB3 share a ClickHandler.

Here the ClickHandler for the A buttons:

ClickHandler clickA = new ClickHandler() {

  @Override
  public void onClick(ClickEvent event) {

  }
});

If one of the Buttons A or B is clicked, how do I know inside the click handler which one of the three FlowPanel groups is affected?


Solution

  • You can evaluate the event source. That should be the button, if you added the click handler to those.

    The button has a name, and the buttons elementId can also be evaluated, and last but not least, the source is the button himself, since you added fields to the buttons, you can ask for identity between thebuttons

    if( ev.getSource() instanceof Button) {
        if(buttonA == (Button)ev.getSource()) ...;
    ...
    

    Another usual pattern is to avoid the what button has been pressed discussion and give a click handler to each of them.

    @UiHandler("buttonA")
    protected void onButtonA(ClickEvent ev) {
        ....
    
    @UiHandler("buttonB")
    protected void onButtonB(ClickEvent ev) {
        ....
    

    If you create the buttons dynamically, you can add the handler dynamically:

    buttonA.addClickHandler( new ClickEventHandler() { ... 
        implement the interface in place