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?
解决方案
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;