-2

可能重复:
为java中的组合框分配键

JComboBox在 Swing 应用程序中使用控件。我必须添加员工代码和他的姓名,JComboBox但我只想显示员工姓名而不是代码。
但是当我选择员工姓名时,它应该返回相应的员工代码。什么是最好和最简单的解决方案。我正在使用以下代码添加项目JComboBox

  try       
   {   
     JComboBox jc1= new JComboBox();
     jc1.addItem("X");
     jc1.addItem("Y");
     jc1.addItem("Z");  

    }

   public void itemStateChanged(ItemEvent ie)
   {
      String code=(String)jc1.getSelectedItem();
       //while items being selected it should return the emp code of the given emp name 
        //eg if user selects X it should return the emp code corresponding to X. 

    }
4

1 回答 1

2

您必须添加 Employee 对象(带有两个成员),而不是将代码添加到 JComboBox。然后您必须创建一个自定义 ListCellRenderer(扩展 DefaultListCellRenderer)来呈现员工姓名。

看看Oracle 的教程

于 2012-10-25T12:05:46.563 回答