4

I have got a Listbox and i want to add some Items. There are only methods to add items as a String, but I want add a Item to the Listbox with a String and a reference to an Object. So that, if a item was selected in the Listbox, I get the Object reference too. Otherwise I have always to search with equal for the right Object.

Is there any option therefore?

tshepang
  • 12,111
  • 21
  • 91
  • 136
ph09
  • 1,052
  • 2
  • 20
  • 31

3 Answers3

8

Try ValueListBox instead of ListBox.

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
2

This is an old question, but since the most elegant answer is not yet here:

// 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);
  }
});
Mark Tielemans
  • 1,528
  • 3
  • 20
  • 40
2

You could store the object in a Map indexed by the value of the item, or in an array or List, at the index of the added item in the list box.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • At the moment I have got a Vector of Objects. Now I want to add them a ListBox. – ph09 Jul 11 '11 at 20:13
  • If you keep the vector in parallel to your listbox, you may get the object at index i in the vector when the item at index i is selected in the listbox. – JB Nizet Jul 11 '11 at 20:16
  • sry I posted too fast ;) At the moment I have got a Vector of Objects. Now I want to add them to the ListBox. When something was selected at the ListBox, I want to get the Object and not a String. Something like: mylistbox.add(String name, MyObject myObject). Or do you mean something like this: int i = myListbox.getSelectedItem(); Myobject object = MyObjectVector.elementAt(i) – ph09 Jul 11 '11 at 20:20
  • Yes, that's exactly what I mean. – JB Nizet Jul 11 '11 at 20:27