Java JComboBox不兼容类型:无法转换为字符串 [英] Java JComboBox Incompatible Types: Cannot be converted to string

查看:137
本文介绍了Java JComboBox不兼容类型:无法转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在JComboBox中添加项目时出现此错误

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

不兼容的类型:ComboBox无法转换为String

incompatible types: ComboBox cannot be converted to String

这是我将数据库中的数据加载到JComboBox的方法...

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);
    }
}

这是课程

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?

推荐答案

不知道如何声明combobox以及在哪一行引发异常,很难确定.

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

我的猜测:combobox被声明为采用String的JComboBox,并且由于添加了ComboBox而不是String,因此将引发异常.

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.

可能的更正:声明JComboBox容纳ComboBox的实例:

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

private JComboBox<ComboBox> combobox;

这篇关于Java JComboBox不兼容类型:无法转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆