简体   繁体   中英

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. 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.

This is the example of the API that works:

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.

You have two choices.

If you're using Java 7 and you've created your JList and ListModel using the correct generics signature. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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