简体   繁体   English

如何获取JList中的选定项目并使用强制转换

[英]How to get the selected item in JList to and use casting

In a part of my program, I have a JList that it has a list on locations, and I got an API that it should use an item from the JList and print out the weather of that location. 在程序的一部分中,我有一个JList ,其中包含位置列表,并且有一个API,它应使用JList的项目并打印出该位置的天气。 So now I can not do it, because I use 所以现在我做不到,因为我使用

WeatherAPI chosen =  locList.getSelectedIndex();

but there is an error: Type mismatch: cannot convert from int to WeatherAPI. 但是出现错误:类型不匹配:无法从int转换为WeatherAPI。

This is the example of the API that works: 这是有效的API的示例:

LinkedList<WeatherAPI> stations = FetchForecast.findStationsNearTo("cityname");
for (WeatherAPI station : stations) {
    System.out.println(station);
}
WeatherAPI firstMatch = stations.getFirst();

So I dont want to get the first option, i want to get the selected location by the user. 所以我不想得到第一个选项,我想得到用户选择的位置。 It's all about casting. 这都是关于铸造的。 I also tried this which did not work: 我也尝试了这个没有用的方法:

WeatherAPI stations;
WeatherAPI firstMatch = stations.get(locList.getSelectedIndex());

I got the rest of the code, that it uses the "firstMatch, but it only uses it when its type is WeatherAPI. 我得到了其余的代码,该代码使用“ firstMatch,但仅在其类型为WeatherAPI时才使用它。

You have two choices. 您有两种选择。

If you're using Java 7 and you've created your JList and ListModel using the correct generics signature. 如果您使用的是Java 7,并且已使用正确的泛型签名创建了JListListModel Assuming something like... 假设像...

JList<WeatherAPI> locList;

And a similar list model declaration, you could use 和类似的列表模型声明,您可以使用

WeatherAPI chosen =  locList.getSelectedValue();

Otherwise you will need to cast the result 否则,您将需要强制转换结果

WeatherAPI chosen =  (WeatherAPI)locList.getSelectedValue();

Been a little old school, I'd typically check the result before the cast 上了一所老学校,我通常会在演员表前检查结果

Object result =  locList.getSelectedValue();
if (result instanceof WeatherAPI) {
    WeatherAPI chosen =  (WeatherAPI)result
}

尝试使用getSelectedValue()

WeatherAPI chosen =  locList.getSelectedValue();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM