public class Item {
private String id;
private String name;
public Item() {
}
public Item(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 重写toString方法,将内容显示在下拉框中
public String toString() {
return getName();
}
}
public class JComboBoxModelTest extends JFrame {
JComboBox jc = new JComboBox();
JLabel jl = new JLabel("请选择证件:");
public JComboBoxModelTest() {
setTitle("在窗口中设置下拉列表框");
Item item = new Item();
item.setId("1");item.setName("aa");
jc.addItem(item);
item = new Item();
item.setId("2");item.setName("bb");
jc.addItem(item);
item = new Item();
item.setId("3");item.setName("cc");
//下拉框直接添加对象,显示时会直接调用Item的toString方法
jc.addItem(item);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(jl);
cp.add(jc);
setSize(new Dimension(160, 180));
setVisible(true);
}
public static void main(String[] args) {
new JComboBoxModelTest();
}
}