Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ComboBox Different Value to Name

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

like image 908
Andreas Christodoulou Avatar asked Apr 30 '12 17:04

Andreas Christodoulou


2 Answers

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;
    }
}
like image 142
JB Nizet Avatar answered Nov 11 '22 13:11

JB Nizet


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;
  }
}
like image 38
eabraham Avatar answered Nov 11 '22 12:11

eabraham