You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

How can I load an image directly from a url?

For example I want to display a picture of a user next to their profile,
but all of the images are served by another machine for better
performance.

    class StaticImage extends WebComponent {

        public StaticImage(String id, IModel model) {
            super(id, model);
        }

        protected void onComponentTag(ComponentTag tag) {
            checkComponentTag(tag, "img");
            tag.put("src", getModelObjectAsString());
        }

    }

    add(new StaticImage("img", new Model("http://foo.com/bar.gif"));

Thanks to Igor Vaynberg

====================================================================

I wanted a simple component that I could pass a URL to and have it display a correctly written img tag.

public class ExternalImageUrl extends WebComponent {

	private String imageUrl;
	
	public ExternalImageUrl(String id, String imageUrl) {
	    super(id);
	    this.imageUrl = imageUrl;
	    add(new AttributeModifier("src", true, new Model(imageUrl)));
	}
	
	public boolean isVisible() {
            return !(imageUrl==null || imageUrl.equals(""));
	}

        protected void onComponentTag(ComponentTag tag) {
            checkComponentTag(tag, "img");
        }

}

Is a little cleaner.

====================================================================

Even with the code above it wasn't obvious for us how to create clickable icons
(serving as external links), which we needed to have as part of the Panel, used
to populate a grid with. Thanks to Igor Vaynberg's hint, we were able to
connect those pieces together. Here is a sample code and related HTML markup
for our Panel component, in case someone needs to do something similar.

public class GridThumbnailPanel extends Panel {
    public GridThumbnailPanel( String id, String label, String iconURL, String linkURL) {
        super( id);
        Label label = new Label( "label", label);
        add( label);
        StaticImage img=new StaticImage( "icon", new Model(iconURL));
        ExternalLink link=new ExternalLink( "link", linkURL);
        link.add(img);
        add( link);
    }
}
<wicket:panel>
    <div wicket:id="label">[test]</div>
    <a wicket:id="link" target="_blank"> <img wicket:id="icon"/> </a>
</wicket:panel>

Please, notice that our panel consists of a label and an icon. To construct
the panel, one needs to supply its wicket id, text for the label and 2 URL-s
(one for the icon itself, another - for the external link). The external
link URL is used to populate the new browser page opened when the icon is
clicked upon, and _blank target is what causes the new browser page to open
after the click.

  • No labels