javaoverridingjcombobox

overriding JComboBox getSelectedItem is not working


I'm trying to override my JComboBox getSelectedItem method using this static method:

public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
    // query to select ID and TITLE from profiles table
    String query = "SELECT ID,TITRE FROM " + tableName + ";";
    ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
    
    ArrayList visualItems = new ArrayList(); // the Items of my combobox  [item1,item2]
    ArrayList idItems = new ArrayList(); // the corresponding IDs for each item [id1,id2]

    while (myJComboResultSet.next()) {
        visualItems.add(myJComboResultSet.getObject("TITRE")); // filling items set
        idItems.add(myJComboResultSet.getObject("ID")); // filling IDs set
    }
    
    System.out.println("IDItems=" + idItems); // checking that my Items are filled
    System.out.println("visualItems=" + visualItems); // checking that my IDs are filled
    
// creating a combobox of previous items
    jComboBox = new JComboBox(visualItems.toArray()) {
        ArrayList values = idItems;

// overriding the getSelectedItem to return the corresponding selected item's ID
        @Override
        public Object getSelectedItem() {
            Object get = values.get(super.getSelectedIndex());
            System.out.println("get = " + get);
            return get; 
        }

    };

}

I'm calling this method from another frame:

   JComboBoxTools.setupID_TITLE_ComboBox(J_Users_Profile,"profiles");

But when executed it didn't work. the output:

visualItems=[Admin,Teacher,Student]

IDItems=[0,3,5]

the selected item return value is : Teacher

Don't know what to do. I want it to return 3 which is the ID of teacher.

the full project is under: this link

thank you.


Solution

  • I get my desired values using a mapComboBoxModel

    public static void setupID_TITLE_ComboBox(JComboBox jComboBox, String tableName) throws SQLException {
    
        String query = "SELECT ID,TITRE FROM " + tableName + ";";
        ResultSet myJComboResultSet = SQLTools.ExecuteQuery(query);
    
        HashMap myMap = new HashMap();
        while (myJComboResultSet.next()) {  
            myMap.put(myJComboResultSet.getObject("TITRE"), myJComboResultSet.getObject("ID"));
        }
    
        jComboBox.setModel(new MapComboBoxModel(myMap) {
    
            @Override
            public Object getValue(Object selectedItem) {
                return map_data.get(selectedItem); //To change body of generated methods, choose Tools | Templates.
            }
    
        });
    
    
    }
    

    I overrided getValue to return the ID .

    if (myComponent instanceof JComboBox) {
                JComboBox jComboBox = (JComboBox) myComponent;
                 MapComboBoxModel model = (MapComboBoxModel) jComboBox.getModel();
                 values+=""+model.getValue(model.getSelectedItem())+",";                
            }