【问题标题】:Why can't I get my combobox to show me my ArrayList?为什么我的组合框不能显示我的 ArrayList?
【发布时间】:2014-05-07 17:33:51
【问题描述】:

我有一个叫CountryList的arraylist,它是一个国家列表,然后我用了代码

jComboBox1.addItem(countries);

尝试将数组列表添加到组合框中,但没有任何反应,没有出现国家列表。

我似乎找不到任何地方说明为什么这不起作用。

这是我被告知应该包含所有国家/地区的代码:

public class CountryList
{

public static void main(String[] args)
{
    List<Country> countries = new ArrayList<Country>();

    Locale[] locales = Locale.getAvailableLocales();
    for (Locale locale : locales)
    {
        String iso = locale.getISO3Country();
        String code = locale.getCountry();
        String name = locale.getDisplayCountry();

        if (!"".equals(iso) && !"".equals(code) && !"".equals(name))
        {
            countries.add(new Country(iso, code, name));
        }
    }

    Collections.sort(countries, new CountryComparator());
    for (Country country : countries)
    {
        System.out.println(country);
    }
}
}

class CountryComparator implements Comparator<Country>
{

private Comparator comparator;

CountryComparator()
{
    comparator = Collator.getInstance();
}

public int compare(Country o1, Country o2)
{
    return comparator.compare(o1.name, o2.name);
}
}

class Country
 {

private String iso;
private String code;
public String name;

Country(String iso, String code, String name)
{
    this.iso = iso;
    this.code = code;
    this.name = name;
}

public String toString()
{
    return iso + " - " + code + " - " + name.toUpperCase();
}
}

编辑

 for (CountryList country : countries)
    {
        jComboBox1.addItem(country);
    }

【问题讨论】:

  • 也许你想添加Country类的元素而不是CountryList类的元素

标签: java swing arraylist jcombobox


【解决方案1】:

您需要一次添加一个国家,而不是整个 ArrayList。您可以遍历每个项目并将其添加到组合框。

for(int i = 0; i < countries.size(); i++) {
        jComboBox1.addItem(countries.get(i));
}

【讨论】:

  • 会是这样吗? (编辑过的 OP)我也试过了,但什么也没有发生
  • 输入时出现错误,提示“需要数组,但已找到 ArrayList。”
  • 我写错了,代码已经更正了。试试看
  • 呃,它仍然是空白的,我不知道为什么。你觉得跟国家名单有关系吗?
  • 我不确定。确保国家不为空。您能否发布将数据添加到国家/地区的代码?
【解决方案2】:

使用默认组合框模型。

jComboBox1.setModel(new DefaultComboBoxModel(countries.toArray()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多