Java ComboBox Different Value to Name

Andreas Christodoulou picture Andreas Christodoulou · Apr 30, 2012 · Viewed 9.4k times · Source

I have a Java combo box and a project linked to an SQLite database. If I've got an object with an associated ID and name:

class Employee {
    public String name;
    public int id;
}

what's the best way of putting these entries into a JComboBox so that the user sees the name of the employee but I can retreive the employeeID when I do:

selEmployee.getSelectedItem();

Thanks

Answer

JB Nizet picture JB Nizet · Apr 30, 2012

First method: implement toString() on the Employee class, and make it return the name. Make your combo box model contain instances of Employee. When getting the selected object from the combo, you'll get an Employee instance, and you can thus get its ID.

Second method: if toString() returns something other than the name (debugging information, for example), Do the same as above, but additionally set a custom cell renderer to your combo. This cell renderer will have to cast the value to Employee, and set the label's text to the name of the employee.

public class EmployeeRenderer extends DefaulListCellRenderer {
    @Override
    public Component getListCellRendererComponent(JList<?> list,
                                                  Object value,
                                                  int index,
                                                  boolean isSelected,
                                                  boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        setText(((Employee) value).getName());
        return this;
    }
}