I needed to create an anchor to an external site in GWT, but display an image in that anchor instead of text. I was surprised this widget wasn’t included in standard set offered by GWT. But it turned out to be an easy thing to implement.
Here’s what it is, as shown in Firebug. It is an anchor that surrounds an image:
Sample Code
ImageAnchor.java
This class is the implementation of the actual widget. It needs to be in some spot in your project. Note that this implementation assumes you are using the ImageResource facility. You could also provide the image via URL, by adding a setUrl() method to ImageAnchor, and changing the Image() constructor to take a String url.
package com.tendril.ui.components.reward.client.view;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.DOM;
public class ImageAnchor extends Anchor {
public ImageAnchor() {
}
public void setResource(ImageResource imageResource) {
Image img = new Image(imageResource);
img.setStyleName("navbarimg");
DOM.insertBefore(getElement(), img.getElement(), DOM
.getFirstChild(getElement()));
}
}
UiBinder XML
You don’t have to use UiBinder templating for this. It is optional. But if you are using UiBinder, this is how it goes:
Add the package to your namespaces at the top of the document. I use the rw namespace in my case:
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:rw="urn:import:com.tendril.ui.components.reward.client.view"
>
Then you can use your widget. For example:
<g:HTMLPanel addStyleNames='{resources.style.redeem_button_div}'>
<rw:ImageAnchor resource="{resources.redeem_button}"
ui:field="redeemButton" />
</g:HTMLPanel>
View
You can interact with the widget in your view just like any other Anchor. If fact, for my purposes, I declare it as an Anchor supertype.
@UiField
Anchor redeemButton;
Nice work - I've used it a couple of times now.
ReplyDeletecheers,
Ian
yes, good work, thanks for this.
ReplyDeleteI was also surprised to find it not in the standard API.
cheers,
Doug
Thank you very much for this simple yet convenient class.
ReplyDelete