首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

swing 中替JComboBox增加存取value显示name的办法

2012-10-07 
swing 中为JComboBox增加存取value显示name的办法//定义数据结构class City{????? private String name??

swing 中为JComboBox增加存取value显示name的办法

//定义数据结构

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<City> listCity = new ArrayList<City>();

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吧

热点排行