JComboBox的值

是否可以定义与JComboBox中的实际内容不同的值?
在HTML中,它看起来如下:

 Content1 Content2 Content3  

无论内容多长,都可以获得一个简短的值。

在Java中我只知道以下解决方案:

 // Creating new JComboBox with predefined values String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" }; private JComboBox combo = new JComboBox(petStrings); // Retrieving selected value System.out.println(combo.getSelectedItem()); 

但在这里我只会得到“猫”,“狗”等。

问题是,我想将数据库中的所有客户名称加载到JComboBox中,然后从所选客户中检索ID。 它应该如下所示:

  Peter Smith Jake Moore Adam Leonard  

如果您创建一个Customer类并将一个Customer对象列表加载到combobox中,那么您将获得所需的内容。 combobox将显示对象的toString(),因此Customer类应返回toString()中的名称。 当您检索所选项目时,它是一个Customer对象,您可以从中获取ID或您想要的任何其他内容。


这是一个例子来说明我的建议。 但是,当你得到这个基本想法时,遵循kleopatra和mKorbel的建议是个好主意。

 import java.awt.BorderLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class ComboJumbo extends JFrame{ JLabel label; JComboBox combo; public static void main(String args[]){ new ComboJumbo(); } public ComboJumbo(){ super("Combo Jumbo"); label = new JLabel("Select a Customer"); add(label, BorderLayout.NORTH); Customer customers[] = new Customer[6]; customers[0] = new Customer("Frank", 1); customers[1] = new Customer("Sue", 6); customers[2] = new Customer("Joe", 2); customers[3] = new Customer("Fenton", 3); customers[4] = new Customer("Bess", 4); customers[5] = new Customer("Nancy", 5); combo = new JComboBox(customers); combo.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e) { Customer c = (Customer)e.getItem(); label.setText("You selected customer id: " + c.getId()); } }); JPanel panel = new JPanel(); panel.add(combo); add(panel,BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 200); setVisible(true); } class Customer{ private String name; private int id; public Customer(String name, int id){ this.name = name; this.id = id; } public String toString(){ return getName(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } } 

假设您有一个包含名称和ID的Person类,您可以将此类的实例添加为combobox的对象。 然后getSelectedItem()将返回所选Person的实例。

问题是在combobox中正确显示人。 您可以在类中重载toString以返回名称,或者您可以将自己的ListCellRenderer给combobox并在combobox中呈现您想要的任何内容(例如,照片缩略图)。

我刚刚在https://stackoverflow.com/a/10734784/11961上回答了另一个问题,该问题解释了创建自定义ListCellRenderer的好方法,该自定义ListCellRenderer用替代标签替换值类上的toString()