combobox key value pair using java

          key value pair combobox example

step 1: Create a class with two variables , key and value

public class customcombo {
String key;
int value;
public customcombo(String key, int value) {
this.key= key;
this.value = value;
public String getKey() {
return key;
public void setKey(String key) {
this.key= key;
public int getValue() {
return value;
public void setValue(int value) {
this.value = value;
public String toString(){
return key;

Step2: set combobox model(static or dynamic)

case 1: static data ,do the following way

Object[] items=new Object[]{new customcombo("INDIA",1),new customcombo("UAE",2),new customcombo("USA",3)};
javax.swing.JComboBox jComboBox1 = new javax.swing.JComboBox();
DefaultComboBoxModel mod=new DefaultComboBoxModel(items);

case 2: dynamic(database) value , do the following way

Object[] items = null;
ResultSet rs = st.executeQuery("select id,country from tb");
if ( {
items = new customcombo[rs.getRow()];
int i = 0;
while ( {
items[i++] = new customcombo(Integer.parseInt(rs.getString(1)), rs.getString(2));

step 3: When program run ,combobox display name(key). To get value of the display name, use the following code

customcombo ob=(customcombo) jComboBox1.getSelectedItem();
Now you get both value
int val=ob.value;
String country=ob.key;