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;
7 comments:
Thank you very much!
Nice... It solved my problem. Thanks a lot..!
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!
I think this had a problem in the Step 2 -> case 2. Need to invert the key value order to run.
Thank you so much for this. New to Java. After looking at many many solutions, this worked like a charm. If I can request, for others that might use this. In the Dynamic(database) option Step 2. The following lines need to be added.
javax.swing.JComboBox jComboBox1 = new javax.swing.JComboBox();
DefaultComboBoxModel mod=new DefaultComboBoxModel(items);
jComboBox1.setModel(mod);
THANK YOU ONCE AGAIN.
Thanku Very much , it solved my issue, but how to retrive values and names on any event???
Thanks u so much, i ve been other methods without succes. Yours is working well; good job!!!
Post a Comment