How to get the selected item in JList to and use casting

Alex Jj picture Alex Jj · Mar 30, 2013 · Viewed 16.9k times · Source

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.

Answer

MadProgrammer picture MadProgrammer · Mar 30, 2013

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
}