Is it possible, to define values different from the actual content in a JComboBox?
In HTML it looks as follows:
<select>
<option value="value1">Content1</option>
<option value="value2">Content2</option>
<option value="value3">Content3</option>
</select>
Here it’s possible to get a short value, no matter how long its content is.
In Java I only know the following solution:
// Creating new JComboBox with predefined values
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
private JComboBox combo = new JComboBox(petStrings);
// Retrieving selected value
System.out.println(combo.getSelectedItem());
But here I only would get “Cat”, “Dog”, etc.
The problem is, that I want to load all names of the customers from a database into the JComboBox and then retrieve the ID from the selected customer. It should look like this:
<select>
<option value="104">Peter Smith</option>
<option value="121">Jake Moore</option>
<option value="143">Adam Leonard</option>
</select>
If you create a Customer class and load a list of Customer objects into the combobox then you will get what you want. The combo box will display the toString() of your object, so the Customer class should return the name in toString(). When you retrieve the selected item its a Customer object from which you can get the id or whatever else you want.
Here is an example to illustrate what I am suggesting. However, it would be a good idea to follow kleopatra’s and mKorbel’s advice when you get this basic idea working.