Search code examples
javadatabasecomboboxfield

Java Combobox, Managing 2 fields from database


I want to get a result set with 2 fields from my DB.

 rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");

And then I want to show the field called "name_prov" in the comboBox (As the item). But I also want to have my "id_prov" which is the ID (PRIMARY KEY) as the value for this item. This serves for the purpose of relating the name (of the providers in this case) with its ID just by using the combobox.

This is the code of the JComboBox event FocusGained that Im currently using.

try {
        //CBProv is the Combobox
        CBProv.removeAllItems();


        rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");

        while(rs.next())
        {

            CBProvedores.addItem(rs.getString("name_prov"));
            //Here should be the Value related to the item I am creating



        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Error" + e  );
    }

Is there anyway I can accomplish this?


Solution

  • First create a POJO, which will hold both your name and id.

    public class ComboItem {
        private String id;
        private String name;
    
        public ComboItem(String id, String name) {
            this.id = id;
            this.name = name;
        }
    
        // Add the getter and setter as you want.
    
        // This will be used internally by JComboBox as the label to be displayed.
        @Override
        public String toString() {
            return name;
        }
    }
    

    Then use this POJO objects to be put into your JComboBox.

    try {
            //CBProv is the Combobox
            CBProv.removeAllItems();
    
            rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
    
            while(rs.next())
            {                
                String id = rs.getString("id_prov"); // Get the Id
                String name = rs.getString("name_prov"); // Get the Name
    
                ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
                CBProv.addItem(comboItem); // Put it into the ComboBox
    
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error" + e  );
        }
    

    And then finally to get the value selected, you can do this:-

    CBProv.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    ComboItem comboItem = (ComboItem) CBProv.getSelectedItem();
                    // comboItem.getId(), comboItem.getName() - Use as you wish.
                }
        });