Search code examples
javaswingjcombobox

jCombo Box With Hidden Data java


I've searched on how to put extra data in jComboBox in java, the most results that I've found is to create an Item Class that contains to attributes key and value.

I've done that but i'm still having this error whene i'm trying to add item in jComboBox with `new Item(key, value),

error code is :

Item cannot be converted to String jComboTemp1.addItem(new Item("CA", "Canada"));

Here is the class Item :

public class Item {

    private int id;
    private String description;

    public Item(int id, String description) {
        this.id = id;
        this.description = description;
    }

    public int getId() {
        return id;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return description;
    }
}

The problem shows here although i've override toString methode :

jComboTemp1.addItem(new Item<String>("CA", "Canada"));

Solution

  • You have several problems:

    public class Item {
    

    The class does not use generic.

    public Item(int id, String description) {
    

    The constructor is expecting an "int" and a "String".

    jComboTemp1.addItem(new Item<String>("CA", "Canada"));
    

    When you create the Item object you have two mistakes:

    1. You are attempting to use generics
    2. You pass the wrong parameters.

    So you have two solutions. You need to either:

    1. Use generics properly, or
    2. Don't use generics.

    If you don't use generics then you need to pass the proper parameters to the Item object:

    jComboTemp1.addItem(new Item(1, "Canada"));
    

    If you do want to use generics, then you need to modify the Item class to use generics.

    Check out the Item class found in Combo Box With Hidden Data for a generic Item object. This object is a more complete implementation since it also implements the equals(...) and hashcode() methods.

    Using the Item class from the above link if you want to have Integer data in your Item class you would use:

    JComboBox<Item<Integer>> jcomboTemp1 = new JComboBox<Item<Integer>>();
    ...
    jcomboTemp1.addItem(new Item<Integer>(1, "Canada"));  
    

    Using a generic object is a little more complicated but you get the added safety of compile time checks to make sure you add the proper data to the class.

    A generic class is more reusable. You could easily change the code to be:

    JComboBox<Item<String>> jcomboTemp1 = new JComboBox<Item<String>>();
    ...
    jcomboTemp1.addItem(new Item<String>("CA", "Canada"));  
    

    and now the class supports a hidden value in a String format and no change was needed to the Item class.