【问题标题】:HashMap into DefaultListModelHashMap 到 DefaultListModel
【发布时间】:2012-02-28 00:14:58
【问题描述】:

这是我的代码:

HashMap<String, String> inst1 = new HashMap(instructorIO.getInstructors());
instListModel = new DefaultListModel<String>(inst1.values());

我收到错误:

DepartmentProject.java:69: error: constructor DefaultListModel in class DefaultListModel<E> cannot be applied to given types;
    required: no arguments
    found: Collection<String>
    reason: actual and formal argument lists differ in length
    where E is a type-variable:
    E extends Object declared in class DefaultListModel

谁能帮我解决这个问题?

【问题讨论】:

  • DefaultListModel 不带任何参数,您将其传递给一个集合。
  • 有没有办法将 hashmap 中的每个值放入列表模型中?
  • 您需要将元素添加到ListModel,因此遍历您的HashMap 并将每个值添加到ListModel
  • 当我对 (a.getValue()) 进行循环并尝试将它们添加到我得到 DepartmentProject.java:72: 错误:类 DefaultListModel 中的方法 addElement 不能应用于给定类型;实参Object不能通过方法调用转换为String,其中E是类型变量:
  • 我开始工作了,我把它改成了 (a.getValue() + " ");不知何故它通过了

标签: java hashmap defaultlistmodel


【解决方案1】:

DefaultListModel 只有一个不带参数的构造函数;您不能将所需的值作为构造函数 arg 传递。 您必须创建 DefaultListModel,然后再填充它,例如:

HashMap<String, String> inst1 = new HashMap(instructorIO.getInstructors());
instListModel = new DefaultListModel<String>();
for (String value : inst1.values())
{
    instListModel.addElement(value);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2014-11-11
    • 1970-01-01
    相关资源
    最近更新 更多