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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15723134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:38:48  来源:igfitidea点击:

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

javaswingcastingjlistgetselection

提问by Alex Jj

In a part of my program, I have a JListthat it has a list on locations, and I got an API that it should use an item from the JListand print out the weather of that location. So now I can not do it, because I use

在我的程序的一部分中,我有一个JList关于位置的列表,我得到了一个 API,它应该使用来自 的项目JList并打印出该位置的天气。所以现在我不能这样做,因为我使用

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 时才使用它。

回答by MadProgrammer

You have two choices.

你有两个选择。

If you're using Java 7 and you've created your JListand ListModelusing the correct generics signature. Assuming something like...

如果您使用的是 Java 7 并且您已经创建JListListModel使用了正确的泛型签名。假设类似...

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
}

回答by Walery Strauch

Try to use getSelectedValue():

尝试使用getSelectedValue()

WeatherAPI chosen =  locList.getSelectedValue();