This code is from the Wicket in Action book.
final WebMarkupContainer parent = new WebMarkupContainer("comments");
parent.setOutputMarkupId(true);
add(parent);
List<String> comments = ...
parent.add(new ListView("list", comments) {
@Override
protected void populateItem(ListItem item) {
item.add(new Label("comment", item.getModel()));
}
});
Form form = new Form("form");
final TextArea editor = new TextArea("editor", new Model(""));
editor.setOutputMarkupId(true);
form.add(editor);
form.add(new AjaxSubmitLink("save") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form form) {
comments.add(editor.getModelObjectAsString());
editor.setModel(new Model(""));
target.addComponent(parent);
target.focusComponent(editor);
}
});
parent.add(form);
It doesn’t compile. Inside the override method, the row
comments.add(editor.getModelObjectAsString());
generates the following errors in Eclipse
“Multiple markers at this line. Cannot refer to a non-final variable comments inside an inner class defined in a different method. The method getModelObjectAsString() is undefined for the type TextArea.”
I love programming books written by the authors of a framework with examples that don’t work =) seriously though, what is wrong here and how can it be fixed?
EDIT:
In order for it to compile in Wicket 1.4, the code needs to change to
/* Java code */
final WebMarkupContainer parent = new WebMarkupContainer("comments");
parent.setOutputMarkupId(true);
add(parent);
final List<String> comments = new ArrayList<String>();
parent.add(new ListView("list", comments) {
@Override
protected void populateItem(ListItem item) {
item.add(new Label("comment", item.getModel()));
}
});
Form form = new Form("form");
//final TextArea editor = new TextArea("editor", new Model(""));
final TextArea editor = new TextArea("editor", new Model(""));
editor.setOutputMarkupId(true);
form.add(editor);
form.add(new AjaxSubmitLink("save") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form form) {
comments.add((String) editor.getModelObject());
editor.setModel(new Model(""));
target.addComponent(parent);
target.focusComponent(editor);
}
});
parent.add(form);
But if the list is made final, then wont it be impossible to dynamically alter its contents?
Putting my comment into a real answer:
The problem is the not the final on the TextArea, but that the Wicket in Action book is written for Wicket 1.3 and the APi has changed for version 1.4 / 1.5.
The migration guide for Wicket i.4 states that the members have been renamed to getDefaulModelXXX().
Have fun with wicket.