Tuesday, January 24, 2012

External Image in Wicket

This component allows creating an image that is loaded from external URL. All we need is to instantiate a new ExternalImage component by passing image URL to constructor and add it on a page.

Source code

package web.images;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.WebComponent;
import org.apache.wicket.model.Model;

/**
 * Creates external image
 * @author sergej.sizov
 */
public class ExternalImage extends WebComponent {

    public ExternalImage(String id, String imageUrl) {
        super(id);
        add(AttributeModifier.replace("src", new Model(imageUrl)));
        setVisible(!(imageUrl==null || imageUrl.equals("")));
    }
   
    @Override
    protected void onComponentTag(ComponentTag tag) {
            super.onComponentTag(tag);
            checkComponentTag(tag, "img");
    }

}

Usage

WebComponent image = new ExternalImage ("image", "http://example.com/logo.jpg");
add(image);

Additionally we can add/modily tag attributes using AttributeModifiers

image.add(AttributeModifier.replace("alt", "Image alternative text");



1 comment:

  1. You should also add your html example here.
    Is it <img wicket:id="image"> or something else. Nice example.

    ReplyDelete