I don’t know if this is possible.
// Adding values to a listbox in Java
DefaultListModel<String> model = new DefaultListModel<String>();
model.addElement("One");
model.addElement("Two");
list1.setModel(model);
What I want is somehow to store a value in the listbox as follows:
If user clicks on "One", ID=1 is retrieved.
If user clicks on "Two", ID=2 is retrieved.
I know how to retrieve the selected value, but I want to store a hidden ID.
This is easy to do with web based programming but not sure if it could be done with Java.
Yes this is eminently possible, but the key is not to store Strings in the Model but instead objects that hold Strings and id’s, etc.
Assuming a class, MyFoo that holds these fields.
The only kicker is that you’ll want to give the JList a ListCellRenderer that displays only the Number String, but that’s not hard to do, and the tutorials will show you how to do this.
Another solution is to create a
HashMap<String, Integer>that maps the number String with its related int, but I like the first solution better as it seems cleaner to me.