Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get combobox value in Java swing

Tags:

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.

like image 600
vijay Avatar asked Aug 17 '12 03:08

vijay


2 Answers

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

like image 184
Sandeep Avatar answered Sep 18 '22 14:09

Sandeep


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();
like image 27
KV Prajapati Avatar answered Sep 19 '22 14:09

KV Prajapati