我正在尝试创建一个简单的gui天气应用,它消耗BBC rss天气预报,并显示存储在通过网址传递给应用的xml文件中的天气的某些信息。
我已成功使用和解析rss提要,然后在GUI中显示天气信息,但现在我正在尝试实现总结天气描述的天气图标。
在我的weatherParser类中,我编写了一个使用switch case语句的iconChecker方法,根据weatherCode变量更改图标。
weatherCode是通过我的weatherGUI类中的一系列if-else语句确定的,然后我调用iconChecker方法将天气代码和标签作为参数传递。
然而,当我运行gui时,在提供网址并点击预测按钮后,天气数据会输出到gui,但我看不到任何图标。我不确定这是一个简单的解决方案,还是我完全错误,所以任何帮助都会非常感激。
iconChecker方法代码:
/**
* Case switch checks for weather description and selects relevant
* icon to display
* @param weatherCode - each code refers to a different weather state
* @param label - the JLabel to update with relevant icon.
*/
public void iconChecker(int weatherCode, JLabel label) {
switch (weatherCode) {
case 1: ImageIcon veryHot = new ImageIcon("src/main/resources/veryHot.png");
label.setIcon(veryHot);
break;
case 2: ImageIcon cloudyDay = new ImageIcon("src/main/resources/rain.png");
label.setIcon(cloudyDay);
break;
case 3: ImageIcon night = new ImageIcon("src/main/resources/snow.png");
label.setIcon(night);
break;
case 4: ImageIcon snowy = new ImageIcon("src/main/resources/cloudyDay.png");
label.setIcon(snowy);
break;
case 5: ImageIcon storm = new ImageIcon("src/main/resources/night.png");
label.setIcon(storm);
break;
case 6: ImageIcon rain = new ImageIcon("src/main/resources/storm.png");
label.setIcon(rain);
break;
}
}
forecastButton actionPerformed方法代码:
private void forecastButtonActionPerformed(java.awt.event.ActionEvent evt) {
String url = urlField.getText();
int weathercode = 0;
CharSequence sun = "sunny";
CharSequence rain = "rain";
CharSequence snow = "snow";
CharSequence cloud = "cloud";
CharSequence night = "night";
CharSequence storm = "storm";
try {
WeatherParser parser = new WeatherParser();
URL u = new URL(url);
weather = parser.parse(u);
reportBox.setText(weather);
// Each weather description is associated with a weather code
if (weather.contains(sun)) {
weathercode = 1;
}
else if (weather.contains(rain)) {
weathercode = 2;
}
else if (weather.contains(snow)) {
weathercode = 3;
}
else if (weather.contains(cloud)) {
weathercode = 4;
}
else if (weather.contains(night)) {
weathercode = 5;
}
else if (weather.contains(storm)) {
weathercode = 6;
}
else {
weathercode = 0;
}
// Call iconChecker method to update label with relevant icon.
parser.iconChecker(weathercode, iconLabel);
}
catch (ParserConfigurationException | MalformedURLException |
SAXException | XPathException | NullPointerException ex) {}
catch (IOException ex) {}
}