获取Java swing中的combobox值

获取Java swing中的combobox值,java,swing,Java,Swing,我需要在Swing中获取组合框的整数值 我已将一个整数值设置为combobox的id。我尝试了combobox.getSelectedItem()和combobox.getSelectedIndex(),但它无法获取int值 下面是我的代码: CommonBean commonBean[]=new CommonBean[commonResponse.getCommonBean().length+1]; for(int i=0;i<commonRespon

我需要在Swing中获取组合框的整数值

我已将一个整数值设置为combobox的id。我尝试了combobox.getSelectedItem()和combobox.getSelectedIndex(),但它无法获取int值

下面是我的代码:

CommonBean commonBean[]=new CommonBean[commonResponse.getCommonBean().length+1];         
         for(int i=0;i<commonResponse.getCommonBean().length;i++)
         {
             commonBean[i] = new CommonBean("--Please select a project--", 0);
             commonBean[i+1] = new CommonBean(commonResponse.getCommonBean()[i].getProjectName(), commonResponse.getCommonBean()[i].getProjectId());
         }

JComboBox combobox= new JComboBox(commonBean);


public CommonBean(String projectName,int projectId) {       
        this.projectName = projectName;
        this.projectId = projectId;

    }
CommonBean CommonBean[]=新的CommonBean[commonResponse.getCommonBean().length+1];

for(int i=0;iMethod
Object JComboBox.getSelectedItem()
返回一个由
Object
类型包装的值,因此必须相应地强制转换它

语法:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

如果字符串为空,
comboBox.getSelectedItem().toString()
将给出一个
NullPointerException
。因此最好通过
(字符串)进行类型转换

请发布演示问题的帖子。您的更新不完整。例如,
projectId
的类型是什么?当我使用上述内容时,我只得到一个字符串值。(即用户在组合框中看到的名称)。根据更新,它看起来像是
YourType
CommonBean
,从中可以获得
projectId
。没有必要将字符串作为项目,然后进行解析,直接将数字实例放在那里。。。