【发布时间】:2014-06-29 19:43:53
【问题描述】:
我创建了一个简单的检票口表单,其中包含一个 DropDownChoice、一个提交按钮和两个 TextField,以便尝试一些模型链接。 html:
<!DOCTYPE html>
<html xmlns:wicket="http://wicket.apache.org">
<head>
<meta charset="utf-8" />
<title>DropDownTest</title>
</head>
<body>
<form wicket:id="selectForm">
<select wicket:id="dropDown"></select>
<input type="submit" wicket:id="bt"/>
<input type="text" wicket:id="age"/>
<input type="text" wicket:id="name"/>
</form>
</body>
</html>
还有java代码:
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
private class Person implements Serializable {
private int age;
private String name;
public Person(){};
public Person(int pAge, String pName) {
age = pAge;
name = pName;
}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
public List<Person> getPersons() {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person(34, "Hanna"));
persons.add(new Person(17, "Ivan"));
persons.add(new Person(64, "Carol"));
return persons;
}
private Form form;
private DropDownChoice<Person> dropDown;
public HomePage(final PageParameters parameters) {
super(parameters);
Model<Person> personModel = new Model<Person>();
dropDown = new DropDownChoice<Person>("dropDown", personModel, getPersons(),
new ChoiceRenderer<Person>("name"));
form = new Form("selectForm");
form.add(new TextField("name", new PropertyModel(personModel, "name")));
form.add(new TextField("age", new PropertyModel(personModel, "age")));
form.add(dropDown);
form.add(new Button("bt"));
add(form);
}
}
下拉选项和两个文本字段共享相同的模型(personModel),因此当用户从下拉选项中选择一个人并单击按钮提交表单并重新加载页面时,这两个字段从通过选择的人那里获取它们的值该模型。这按预期工作,我没有收到任何错误。现在,如果我更改将组件添加到表单的顺序(工作):
form.add(new TextField("name", new PropertyModel(personModel, "name")));
form.add(new TextField("age", new PropertyModel(personModel, "age")));
form.add(dropDown);
到这个(不工作)
form.add(dropDown);
form.add(new TextField("name", new PropertyModel(personModel, "name")));
form.add(new TextField("age", new PropertyModel(personModel, "age")));
提交表单时出现错误:
方法 [public int com.asbjorntest.HomePage$Person.getAge()]。无法将 null 值转换为原始类:int 用于在 com.asbjorntest.HomePage$Person@71460b93 上设置它
我了解错误来自以下事实:我提交的“年龄”文本字段没有任何值,并且无法在我的 Person 类中转换为 int。但是,为什么只有在我在 Java 代码中添加文本字段之前添加 dropdownchoice 时才会发生此错误?或者也许我应该问:为什么在我添加它之后它不会发生?我在 java 代码中将组件添加到表单或页面的顺序是否重要,或者我在这里完全遗漏了什么?
提前感谢任何答案或线索!
【问题讨论】: