Java ComboBox与名称的不同值

And*_*lou 6 java swing combobox jcombobox

我有一个Java组合框和一个链接到SQLite数据库的项目.如果我有一个带有相关ID和名称的对象:

class Employee {
    public String name;
    public int id;
}
Run Code Online (Sandbox Code Playgroud)

将这些条目放入JComboBox的最佳方法是什么,以便用户看到员工的姓名,但是当我这样做时我可以检索employeeID:

selEmployee.getSelectedItem();
Run Code Online (Sandbox Code Playgroud)

谢谢

JB *_*zet 10

第一种方法:toString()在Employee类上实现,并使其返回名称.使您的组合框模型包含Employee的实例.从组合中获取所选对象时,您将获得一个Employee实例,因此您可以获取其ID.

第二种方法:如果toString()返回名称以外的其他内容(例如调试信息),请执行与上面相同的操作,但另外还要为您的组合设置自定义单元格渲染器.此单元格渲染器必须将值强制转换为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;
    }
}
Run Code Online (Sandbox Code Playgroud)


eab*_*ham 6

将employee对象添加到JComboBox并覆盖employee类的toString方法以返回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;
  }
}
Run Code Online (Sandbox Code Playgroud)