在 Java swing 中获取组合框值

2022-09-04 23:46:38

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

我已将整数值设置为组合框的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;

    }

任何帮助是值得赞赏的。


答案 1

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

语法:

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

答案 2

如果字符串为空,将给出一个 .所以最好由.comboBox.getSelectedItem().toString()NullPointerException(String)


推荐