Justine P
Justine P

Reputation: 13

Java JComboBox Incompatible Types: Cannot be converted to string

I have this error when i try to add items in the JComboBox

incompatible types: ComboBox cannot be converted to String

This is my method to load the data from database to the JComboBox...

public final void loadProducts()
{
    try 
    {
        String sql = "SELECT * from product";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();

        while (rs.next())
        {
            combobox.addItem(new ComboBox(rs.getString(2), rs.getString(1)));
        }
        combobox.setSelectedIndex(-1);
    } 
    catch (SQLException ex) 
    {
        System.out.println(ex);
    }
}

And this is the class

public class ComboBox
{
    private String key;
    private String value;

public ComboBox(String key, String value)
{
    this.key = key;
    this.value = value;
}

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

public String getKey()
{
    return key;
}

public String getValue()
{
    return value;
}
}

I have no idea what's causing it! Can someone point out my mistake?

Upvotes: 0

Views: 3378

Answers (2)

Ignatius Chandra
Ignatius Chandra

Reputation: 476

Just change the Type Parameter in Code Properties to ComboBox or whatever your class name that will be put inside .addItem method

enter image description here

Upvotes: 1

user85421
user85421

Reputation: 29680

It is hard to be certain without knowing how combobox is declared and at which line the Exception is being thrown...

My guess: combobox is declared as a JComboBox that takes a String and you the Exception is being thrown since a ComboBox is being added instead of a String.

Possible correction: declare the JComboBox to hold instances of ComboBox:

private JComboBox<ComboBox> combobox;

Upvotes: 1

Related Questions