First method: we implement toString()
in the Employee class and force it to return a name. Make your model with a list of Employee instances. Upon receiving the selected object from the combo, you will receive an instance of Employee, and you can get its identifier.
The second method: if toString()
returns something other than the name (for example, debugging information), do the same as above, but additionally set your own cell rendering in your combo. This cell handler will need to assign the value Employee and set the label text to the employee name.
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; } }
source share