Java ComboBox Different Value to Name

十年热恋 提交于 2019-12-07 03:56:29

问题


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


回答1:


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;
    }
}



回答2:


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;
  }
}



回答3:


I think the Best and Simple way to do this would be using HashMap something like this when you are filling your JComboBox with ResultSet

HashMap<Integer, Integer> IDHolder= new HashMap<>();

int a=0;
while(rs.next())
{
    comboBox.addItem(rs.getString(2)); //Name Column Value
    IDHolder.put(a, rs.getInt(1)); //ID Column Value
    a++;
}

Now whenever you want to get the id of any selected comboBox item's id you can do so by simply

int Id = IDHolder.get(comboBox.getSelectedIndex());



回答4:


You can create your custom DefaultComboBoxModel. In that create the vector of your data in your case Vector<Employee> empVec. You need to additionally override the getSelectedItem() method and use the getSelectedIndex() to retrieve the value from the vector.



来源:https://stackoverflow.com/questions/10387932/java-combobox-different-value-to-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!