2011-03-10 23 views
7

que han intentado esto, pero no funcionóCómo agregar clickhandler en ImageCell en GWT CellTable?

Column<ContactInfo, String> imageColumn = new Column<ContactInfo, String>(new ImageCell()) { 
     @Override 
     public String getValue(ContactInfo object) { 
      return "contact.jpg"; 
      } 
     }; 
     imageColumn.setFieldUpdater(new FieldUpdater<ContactInfo, String>() { 

     @Override 
     public void update(int index, ContactInfo object, String value) { 
     Window.alert("You clicked " + object.firstName); 
     } 

    }); 
cellTable.addColumn(imageColumn, SafeHtmlUtils.fromSafeConstant("<br/>")); 
+0

hice solución es utilizar pila de botón en lugar de celda de la imagen a continuación, he cambiado el estilo de la imagen y el botón de fondo, pero a ella. está funcionando bien, dilo ahora. –

Respuesta

1

hice algo similar mezclando una pila de botón con el procesador de un ImageCell ....

ButtonCell bc = new ButtonCell() { 
     @Override 
     public void render(Context context, SafeHtml data, SafeHtmlBuilder sb) { 
      if (data != null) { 
       ImageResource icon = Icons.BUNDLE.pieChart(); 
       SafeHtml html = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(icon).getHTML()); 
       sb.append(html); 
      } 
     } 
    }; 

Usted consigue la idea. El único problema es que no muestra el ícono de "mano" cuando pasas el cursor sobre él ... lo más probable es que se solucione configurando el CSS.

8

Puede ampliar la clase ImageCell y anular 2 sus métodos: getConsumedEvents y onBrowserEvent. Ejemplo:

private class MyImageCell extends ImageCell{ 

    @Override 
    public Set<String> getConsumedEvents() { 
     Set<String> consumedEvents = new HashSet<String>(); 
     consumedEvents.add("dblclick"); 
     return consumedEvents; 
    } 

    @Override 
    public void onBrowserEvent(Context context, Element parent, 
      String value, NativeEvent event, 
      ValueUpdater<String> valueUpdater) { 
      switch (DOM.eventGetType((Event)event)) { 
      case Event.ONDBLCLICK: 
       // TODO 
       break; 

      default: 
       break; 
      } 
    } 

} 
+0

Hay todo tipo de problemas con esto. Para empezar, se trata de hacer doble clic, en lugar de hacer clic. No maneja a las personas ciegas que lo tabulan, etc. Verifique la solución a continuación por mutexkid. –

16
public class ButtonImageCell extends ButtonCell{ 

    @Override 
    public void render(com.google.gwt.cell.client.Cell.Context context, 
      String value, SafeHtmlBuilder sb) { 
     SafeHtml html = SafeHtmlUtils.fromTrustedString(new Image(value).toString()); 
     sb.append(html); 
    } 
} 

en uso:

final Column<ReportDTOProxy, String> buttonImageCellTest = new Column<ProxyObject, String>(new ButtonImageCell()) { 
    @Override 
    public String getValue(ProxyObject row) { 
     //url to image 
     return row.getImageUrl(); 
    } 
}; 
+4

Esta es la mejor solución. Completamente infravalorado. –

1

Puede probar este lugar de utilizar pila de botón o ImageCell. Esto funcionará con seguridad. Como lo he implementado para mi requerimiento. Que me haga saber cómo se va ..

ClickableTextCell imageCell = new ClickableTextCell() { 
     @Override 
     public void render(Context context, SafeHtml data, SafeHtmlBuilder sb) { 
      if (data != null) { 
       String imagePath = "icon.png"; 
       sb.append(imagePath); 
      } 
     } 
    }; 

Column<ContactInfo, String> imageColumn = new Column<ContactInfo, String>(imageCell) { 
     @Override 
     public String getValue(ContactInfo object) { 
      return ""; 
      } 
     }; 
     imageColumn.setFieldUpdater(new FieldUpdater<ContactInfo, String>() { 

     @Override 
     public void update(int index, ContactInfo object, String value) { 
     Window.alert("You clicked " + object.firstName); 
     } 

    }); 
cellTable.addColumn(imageColumn, SafeHtmlUtils.fromSafeConstant("<br/>")); 
+0

funciona como un encanto – Ben

1

Una buena solución para este problema, si utiliza ActionCell que es capaz de manejar clic. El uso de esto es un poco complicado, pero para mí funcionó bastante bien.

Primero debe inicializar ActionCell con un delegado, en el constructor, escriba new ActionCell.Delegate<your class>. En este caso, anule el método execute y escriba su código que maneje el evento de clic.

Lo otro que debe hacer es crear un html a partir de la imagen. La clase SafeHtmlUtils le ofrece una manera muy fácil de hacerlo. Se método fromTrustedString ayuda a construir el html:

SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create ("Your image from a resource class").getHTML()); 

De esta manera el campo SafeHTML puede initalized y si se le da contructor del ActionCell la SafeHTML y el delegado, que va a hacer el trabajo por usted.

En este ejemplo, se inicializará un botón con la imagen del archivo de paquete que contiene. Puede hacerlo sin el botón si anula el método de renderizado de ActionCell y agrega SafeHtmlBuilder en el método con la misma variable SafeHtml que la anterior.

Mi código es el siguiente:

IdentityColumn<Type> imageCell = new IdentityColumn<Type>(new ActionCell<Type>("AnyString", 
       new ActionCell.Delegate<Type>() { 

      @Override 
      public void execute(final Type item) { 
       "your code" 
      } 
     }) { 

      @Override 
      public void render(Context context, Type value, SafeHtmlBuilder sb) { 
       if (value != null) { 
        SafeHtml html = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resource.image).getHTML()); 
        sb.append(html); 
       } 
      } 
     }); 

prefiere reemplazar el método en una otra clase, pero yo no quería separarlos para este post. Me funcionó muy bien, espero que ayude a otros también.

1

Obtuve todo lo anterior y los agregué en mi aplicación. Gracias a todos. stackoverflow rocks!

ButtonCell bc = new ButtonCell() { 
     @Override 
     public void render(Context context, SafeHtml data, SafeHtmlBuilder sb) { 
      if (data != null) { 
       ImageResource icon = Connector.imageResources.minus(); 
       Image image = new Image(icon); 
       //fix the mouse pointer 
       image.getElement().getStyle().setCursor(Cursor.POINTER); 
       //Do something with the DATA 
       image.setTitle("Delete " + data.asString()); 
       SafeHtml html = SafeHtmlUtils.fromTrustedString(image.toString()); 
       sb.append(html); 
      } 
     } 
    }; 
    Column<InstanceProperty, String> imageColumn = new Column<InstanceProperty, String>(bc) { 
     @Override 
     public String getValue(InstanceProperty object) { 
      //return the DATA 
      return object.getKey(); 
     } 
    }; 
    imageColumn.setFieldUpdater(new FieldUpdater<InstanceProperty, String>() { 
     @Override 
     public void update(int index, InstanceProperty property, 
       String value) { 
      //you can also use the DATA to do something 
      InstancePropertiesTable.this.dataProvider.getList().remove(index); 
     } 
    }); 
    addColumn(imageColumn, ""); 
+0

Hola amigo ... eres increíble ... muchas gracias ... te di un voto positivo. Ummaaa – nmkyuppie

0

Esto funcionó para mí:

public class ButtonImageCell extends ButtonCell{ 
    @Override 
    public void render(com.google.gwt.cell.client.Cell.Context context, 
     String renderedHtmlStr, SafeHtmlBuilder sb) { 
     sb.appendHtmlConstant(renderedHtmlStr); 
    } 
} 

En una clase que contiene CellTable table:

TableResources resources = GWT.create(TableResources.class); 
ImageResourceRenderer imageRenderer = new ImageResourceRenderer(); 

...

Column<MyRecord, String> buttonCol = new Column<MyRecord, String>(new ButtonImageCell()) { 
    @Override 
    public String getValue(MyRecord record) { 
     if(record.isOn()) 
      return imageRenderer.render(resources.getOnImg()).asString(); 
     else 
      return imageRenderer.render(resources.getOffImg()).asString(); 
    } 
}; 

buttonCol.setFieldUpdater(new FieldUpdater<MyRecord, String>() { 
    public void update(int index, MyRecordobject, String value) { 
     if (Window.confirm("Do stuff?")) { 
      //todo: stuff 
     } 
    } 
}); 

...

table.addColumn(buttonCol, ""); 

Cuando el ImageResource proviene de (resources):

public interface TableResources extends CellTable.Resources { 

    interface TableStyle extends CellTable.Style { 
    } 

    @Source("/images/on.png") 
    ImageResource getOnImg(); 

    @Source("/images/off.png") 
    ImageResource getOffImg(); 
} 
Cuestiones relacionadas