//从CityList.xml文件中加载城市列表
public void initCityList(){}
//主方法
public static void main(String args[])
{new YahooWeatherFramePre();}
}
上述代码中“ImageIcon("img/ico.png")”加载了窗体的logo图片,因此要将ico.png图片文件存放到img文件夹下,img文件夹放置在class包所在目录下,否则程序不能正确执行。
在完成了代码框架的开发后就可以开发加载城市列表XML文档CityList.xml的initCityList方法了,其代码如下:
public void initCityList()
{
try
{
// 为解析XML文件创建DOM对象
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
//解析XML文件
Document doc =
builder.parse(new File("CityList.xml"));
// 规格化
doc.normalize();
//解析城市列表
NodeList cityItems =
doc.getElementsByTagName("cityItem");
int cityCount=cityItems.getLength();
CityItem[] cia=new CityItem[cityCount];
for(int i=0;i<cityCount;i++){
Element cityElement =
(Element)cityItems.item(i);
String ccode=
cityElement.getElementsByTagName("code")
.item(0).getFirstChild().getNodeValue();
String cname=
cityElement.getElementsByTagName("name")
.item(0).getFirstChild().getNodeValue();
cia[i]=new CityItem(cname,ccode);}
jcb.setModel(
new DefaultComboBoxModel(cia));
}catch(Exception e){e.printStackTrace();}
}
上述initCityList方法将CityList.xml文件中的每个cityItem加载为一个CityItem类对象,并添加到CityItem数组中,最终将数组添加到DefaultComboBoxModel对象以显示到下拉列表中。完成YahooWeatherFramePre类的开发后,将代码编译运行一下,可以见到如图1所示的城市列表选择窗体。
|