我有一个Listbox,我想添加一些项目。 只有将项添加为String的方法,但是 我想使用String和对Object的引用将List添加到Listbox。 因此,如果在列表框中选择了一个项目,我也会获得Object引用。 否则我总是用相同的对象搜索。
是否有任何选择?
答案 0 :(得分:7)
尝试使用ValueListBox
代替ListBox
。
答案 1 :(得分:2)
您可以将对象存储在由项目值索引的Map中,或者在数组或List中,在列表框中添加项目的索引处。
答案 2 :(得分:2)
这是一个老问题,但由于最优雅的答案还没有在这里:
// Applicable for an object of specified type 'User'
ValueListBox<User> lbUser = new ValueListBox<User>(new Renderer<User>() {
public String render(User user) {
String s = "";
if (user != null) {
// Specify the format for the Strings to display per list item here. In this example, it is
// 'username (firstname lastname)'
// For example: MTielemans (Mark Tielemans)
s = user.getUsername() + "("+user.getFirstname()+" " + user.getLastname()+")";
} else {
s = "Select a user";
}
return s;
}
public void render(User user, Appendable appendable) throws IOException {
String s = render(user);
appendable.append(s);
}
});