views:

230

answers:

3

I have a table in a database that contains two fields

  • id
  • name

I have populated a JComboBox "combo1" with all the names stored in the DB. Now I want that whenever a user selects an item of the "combo1", I can recognize the "id" of the selected item.

But the problem is that names can be duplicates in a table. So let assume if a table has 3 duplicate names, then

Q1. How to show the items in the "combo1" so that user can distinguish between those common names?

Q2. After the user has clicked an item, How can I recognize that on which item the user has clicked, if the selected item has duplicates?

+1  A: 

If you get all the id/name combinations, why not make a class that holds them both together, then you can just use that object returned from the JComboBox to get the ID.

eg:

class NameIDObj{

int id;
String name;

NameIDObj(int id, String name){
this.id = id;
this.name = name;
}

public String toString(){
 return name+" ("+id+")";
}


}
Kylar
+1  A: 

use a class to store your pair of data. JComboBox will use its toString() method as the label.

public class Item
{
int id;
String name;
public toString()
  {
  return this.name+"("+id+")";
  }
}
(...)
Item array[]=new  Item[]{ ... };//fill the array with your items
JComboBox c=new  JComboBox(array);
(...)
//use the combo
(...)
Item selected=(Item)c.getSelectedItem();
System.err.println("id is "+selected.id);
Pierre
+1  A: 

JComboBox takes in an Object[] as its values. I am not absolutely certain but you could try creating your own class that has a name and an id for each JComboBox item and try passing an array of these custom objects to the JComboBox.

Prachi