在Jcombo Box上添加项目[复制]

时间:2023-01-28 11:19:41

Possible Duplicate:
assign keys for combo box in java

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

I am using JComboBox control in a Swing application. I have to add employee code and his name on JComboBox but i want to display only employee name not the code.
but when i select the employee name it should return the corresponding employee code. what is the best and easy solution for it. I am using the following code for adding the items on JComboBox

我在Swing应用程序中使用JComboBox控件。我必须在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. 

    }

1 个解决方案

#1


2  

Instead of adding the code to the JComboBox, you have to add the Employee object (with the two members). Then you have to create a custom ListCellRenderer (extending DefaultListCellRenderer) to render the employee name.

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

Take a look at Oracle's tutorial.

看看Oracle的教程。

#1


2  

Instead of adding the code to the JComboBox, you have to add the Employee object (with the two members). Then you have to create a custom ListCellRenderer (extending DefaultListCellRenderer) to render the employee name.

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

Take a look at Oracle's tutorial.

看看Oracle的教程。