Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map the JComboBox item to its corresponding ID?

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?

like image 634
Yatendra Avatar asked Jan 19 '10 18:01

Yatendra


People also ask

Which method is used to add items to JComboBox?

Creates a JComboBox with a default data model. The default data model is an empty list of objects. Use addItem to add items.

Which of these is used to determine whether the JComboBox is editable?

SetEditable() - Determines whether the JComboBox field is editable.

Which is the superclass for JComboBox?

Other methods you are most likely to invoke on a JComboBox object are those it inherits from its superclasses, such as setPreferredSize . See The JComponent API for tables of commonly used inherited methods.

How do I make JComboBox not editable?

u can make ur jcombobox uneditable by calling its setEnabled(false). A JComboBox is unEditable by default. You can make it editable with the setEditable(boolean) command. If you are talking about enabled or disabled you can set that by the setEnabled(boolean) method.


2 Answers

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 String 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);
like image 71
Pierre Avatar answered Sep 24 '22 23:09

Pierre


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+")";
}


}
like image 31
Kylar Avatar answered Sep 22 '22 23:09

Kylar