在Java swing中获得combobox值

我需要在Swing中获得combobox的整数值。

我已经为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; } 

任何帮助表示赞赏。

方法Object JComboBox.getSelectedItem()返回一个由Object类型包装的值,因此您必须相应地进行转换。

句法:

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

如果字符串为空,则comboBox.getSelectedItem().toString()将给出NullPointerException 。 因此(String)更好地进行类型转换。