Java ComboBox不同的值到名称 [英] Java ComboBox Different Value to Name

查看:225
本文介绍了Java ComboBox不同的值到名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

什么是将这些条目放入JComboBox的最佳方式,

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();

感谢

推荐答案

第一个方法:在Employee类上实现 toString(),并返回名称。使您的组合框模型包含Employee的实例。

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.

第二种方法:如果 toString()返回除了名称之外的其他名称(例如调试信息),执行与上面相同的操作,但是另外设置一个自定义单元格渲染器到你的组合。此单元格渲染器必须将值转换为Employee,并将标签的文本设置为员工的名称。

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

这篇关于Java ComboBox不同的值到名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆