Wicket: a convenient shortcut

When using Apache Wicket, much code is spent on building the component tree. You instantiate the components, and add them to their parent component. Then you take these new components, and add further components. This often looks like this:

Link<Void> l = new Link<Void>("linkid") {...};
add(l);
l.add(new Label("linklabelid", linktext));

Often, I forget the second line… so I want to have a shorter version. add returns the this component, which allows for chaining multiple component additions (as you chain calls to StringBuilder.append), but you cannot get a reference to the added child component directly.

So here is a small utility method that will allow you to do just that:

public class WicketUtils {
	public static <T extends Component> T add(MarkupContainer target, T object) {
		target.add(object);
		return object;
	}
}

Small and simple.. but you can shorten the code above to two lines:

Link<Void> l = WicketUtils.add(this, new Link<Void>("linkid") {...});
l.add(new Label("linklabelid", linktext));

This is more convenient, and tidies up the code. I have to admit, this is almost too trivial, but once I started using it consistently, it helped quite a bit.

Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]