java 如何将 ComboBox.SelectedItem() 转换为 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10751891/
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
How to cast a ComboBox.SelectedItem() to int?
提问by alin
I try to cast a ComboBox.SelectedItem() to int and it isn't working. I know that ComboBox.SelectedItem() has the type String and I casted it like this:
我尝试将 ComboBox.SelectedItem() 转换为 int 并且它不起作用。我知道 ComboBox.SelectedItem() 具有 String 类型,我像这样投射它:
int idprovider = ((Integer)IdProviderComboBox.getSelectedItem()).intValue();
but I get the error: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
但我收到错误:java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Maybe someone has an idea. Thanks!
也许有人有想法。谢谢!
回答by mprabhat
You are casting String to Integer hence its throwing ClassCastException, to get int out of a String use one of the following:
您将 String 转换为 Integer,因此它会抛出 ClassCastException,要从 String 中获取 int,请使用以下方法之一:
Update:
更新:
JComboBox.getSelectedItem() will return you Object, to covert it to int use :
JComboBox.getSelectedItem() 将返回您的对象,将其转换为 int 使用:
int idprovider = Integer.valueOf((String)IdProviderComboBox.getSelectedItem()); // Internally calls parseInt, returns Integer, Java converts it to int for you.
int idprovider = Integer.parseInt((String)IdProviderComboBox.getSelectedItem()); // Since you need int use this better