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
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;
}
}
Add the employee object to the JComboBox and overwrite the toString method of the employee class to return Employee name.
Employee emp=new Employee("Name Goes here");
comboBox.addItem(emp);
comboBox.getSelectedItem().getID();
...
public Employee() {
private String name;
private int id;
public Employee(String name){
this.name=name;
}
public int getID(){
return id;
}
public String toString(){
return name;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With