Friday, June 1, 2012

Table Cell Background Image in Wicket

HTML code for TD background image:
<td style="background-image: url(abc.png); background-repeat: no-repeat;">

Wicket code for generating this code:

First step is to obtain the URL of the background image. Let's say this time the image is in the package (i.e. together with the Java & HTML classes for a more object-oriented approach).

PackageResourceReference bgImageResource = new PackageResourceReference(this.getClass(),"abc.png");
String imageUrl = RequestCycle.get().urlFor(bgImageResource, new PageParameters()).toString();

imageUrl is the relative path from the context root to the image file. However, this URL will not work as-is, as the current page is unlikely to be on the context root.

To generate full URL:

imageUrl = RequestCycle.get().getRequest().getContextPath() + "/" +imageUrl;
getContextPath is new in Wicket 1.5.

Lastly, create the style attribute with an AttributeModifier.

tdElement.add(new AttributeModifier("style", "background-image:url("+imageUrl+");background-repeat: no-repeat;"));

No comments:

Post a Comment