vijay
vijay

Reputation: 667

Get combobox value in Java swing

I need to get the integer value of the combobox in Swing.

I have set an integer value as id for the combobox.I tried combobox.getSelectedItem() and combobox.getSelectedIndex() but it cant get the int value.

Below is my code:

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;

    }

Any help is appreciated.

Upvotes: 13

Views: 220384

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94653

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

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

Upvotes: 50

Sandeep
Sandeep

Reputation: 71

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Upvotes: 7

Related Questions