---
title: "swing 中为JComboBox增加存取value显示name的办法"
author: "hsyd"
date: "2011-09-23T16:44:23Z"
tags: []
categories: ["编程语言"]
slug: "swing-jcombobox-value-name"
draft: false
lastmod: "2011-09-23T16:44:23Z"
id: 1179149
url: "https://hsyd.iteye.com/blog/1179149"
---

//定义数据结构

class City{

      private String name;

      private int code;

      public City(name,code){......}

      //...getter、setter省略

      public String toString(){

             return name;

      }

      //equals 方法 ...return this.code==other.code

}

// 创建

List&lt;City&gt; listCity = new ArrayList&lt;City&gt;();

listCity.add(new City("北京",1));

listCity.add(new City("上海",2));

listCity.add(new City("广州",3));

listCity.add(new City("none",-1));

JComboBox jcbCity = new JComboBox(listCity.toArray());

这样下拉选择框就建好了，显示的文本是City.toString()得到的值（这里显示的是name）

 

JComboBox有一组方法：

void setSelectedItem(Object) ： 选中object这个项目

Object getSelectedItem() ：取得选中的项目对象(这个例子中getSelectedItem就能拿到City对象)

 

使用：

1\. 取得当前选中的City 的名字

City selectedCity =(City) jcbCity.getSelectedItem();

String cityName = selectedCity.getName();

 

2\. 选中值为aCity的项目（aCity是其它地方取得的）

jcbCity.setSelectedItem(aCity);

 

3.知道code=2，要选择对应的项目

jcbCity.setSelectedItem(new City("",2));//应该没忘记equals方法只是比较code吧