在Java swing中获得组合框值

vij*_*jay 12 java swing

我需要在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;

    }
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.

ada*_*ost 44

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

句法:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();
Run Code Online (Sandbox Code Playgroud)


小智 6

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