如何从对象列表中获取特定属性?
我有一个数组,保存 Group
对象的列表。我想将此列表设置为 DropDownChoice
组件。但是,我想仅向最终用户显示 Group
对象的 name 属性,然后获取所选值的 id 属性以添加数据库。该怎么办?
private List<Group> groupTypes;
DatabaseApp db = new DatabaseApp();
groupTypes = db.getGroups();
groupDropDownChoice = new DropDownChoice("type", groupTypes);
...
...
addUserForm.add(new Button("submit"){
@Override
public void onSubmit(){
Group group = (Group) groupDropDownChoice.getModelObject();
...
...
db.addUser(group.getId(), den, name, login, email, password1);
数据库应用程序.java
public List<Group> getGroups() throws SQLException{
List<Group> groups = new ArrayList<Group>();
try {
String query = "SELECT * FROM [GROUP]";
Statement statement = db.createStatement();
ResultSet result = statement.executeQuery(query);
while(result.next()){
int id = result.getInt("ID");
String name = result.getString("NAME");
groups.add(new Group(id, name));
}
result.close();
} catch (SQLException ex) {
throw new SQLException(ex.getMessage());
}
return groups;
}
I've an array keeping a list of Group
objects. I want to set this list to the DropDownChoice
component. However I want to show the end user only the name attribute of Group
objects, and then get the selected values' id attribute to add database. What to do?
private List<Group> groupTypes;
DatabaseApp db = new DatabaseApp();
groupTypes = db.getGroups();
groupDropDownChoice = new DropDownChoice("type", groupTypes);
...
...
addUserForm.add(new Button("submit"){
@Override
public void onSubmit(){
Group group = (Group) groupDropDownChoice.getModelObject();
...
...
db.addUser(group.getId(), den, name, login, email, password1);
DatabaseApp.java
public List<Group> getGroups() throws SQLException{
List<Group> groups = new ArrayList<Group>();
try {
String query = "SELECT * FROM [GROUP]";
Statement statement = db.createStatement();
ResultSet result = statement.executeQuery(query);
while(result.next()){
int id = result.getInt("ID");
String name = result.getString("NAME");
groups.add(new Group(id, name));
}
result.close();
} catch (SQLException ex) {
throw new SQLException(ex.getMessage());
}
return groups;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DropDownChoice
有另一个构造函数,它接受IChoiceRenderer
的附加参数,该参数允许控制显示的内容以及随表单发送回的内容。请参阅此示例。
在您的代码中,实现可能类似于
DropDownChoice
has another constructor accepting an additional parameter of anIChoiceRenderer
that allows control of what's displayed and what's sent back with the form.See this example.
In your code, an implementation could look approximately like
您只需直接从组列表创建
DropDownChoice
即可。在我看来,您真正想要的是组列表的模型;请参阅IModel
文档。然后,您可以创建一个仅返回组名称而不是整个Group
对象的自定义模型。You're just creating the
DropDownChoice
directly from the list of groups. It seems to me that what you really want is a model for the list of groups; see theIModel
documentation. Then you can create a custom model that returns only the name of a group instead of the wholeGroup
object.