Java JComboBox Incompatible Types: Cannot be converted to string

孤街浪徒 提交于 2020-01-30 11:52:26

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/43029262/java-jcombobox-incompatible-types-cannot-be-converted-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!