Suipaste
Suipaste

Reputation: 420

Accessing elements of an object in a jList/listModel

I'm trying to populate a jList, I want it to display a name but also store an ID (which is not displayed) for each item in the list.

I have created a list model and added each element as an object. The object holds an int value (the ID) and a string value (the name):

doorListModel.addElement(nextDoor);

Once all the elements have been added I then send this model to the jList:

jList1.setModel(doorListModel);

When you run the program the jList appears to just show a memory location for each element: Current jList output

How can I get the jList to just display the String value and, (assuming this is possible) how do I access the hidden int value if I was to select an item from the jList.

Cheers.

Upvotes: 0

Views: 954

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You've got two options as I see it:

  • You can give your Door class a decent toString() method since this is what the JList displays by default, or
  • Give your JList a decent ListCellRenderer. This is the recommended solution since a toString() result really shouldn't be used for production purposes but rather for debugging.

Upvotes: 4

Related Questions