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;
}
@Override
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);
jComboBox1.setModel(mod);

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

Object[] items = null;
ResultSet rs = st.executeQuery("select id,country from tb");
if (rs.next()) {
rs.last();
items = new customcombo[rs.getRow()];
rs.beforeFirst();
}
int i = 0;
while (rs.next()) {
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;

4 comments:

niko said...

Thank you very much!

Dhananjaya said...

Nice... It solved my problem. Thanks a lot..!

Adrian Bodolan said...

Hello, I wanted to thank you so much for posting this. I wasn't able to find an optimum solution to my app, but now I finally got it using your example. God bless you!

Antonio Henrique Alves Gomes said...

I think this had a problem in the Step 2 -> case 2. Need to invert the key value order to run.

Post a Comment