为什么我不能直接将 ArrayList 添加到 Jlist? [英] Why I cannot add ArrayList directly to Jlist?

查看:35
本文介绍了为什么我不能直接将 ArrayList 添加到 Jlist?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 ArrayList 添加到 Jlist,但我理解的唯一方法是编写这样的代码:

i am trying to add ArrayList to Jlist, but the only way that I given to understand is that to write the code like this :

ArrayList<String> labels = new ArrayList<String>();
JList jlist = new JList(labels.toArray());

令我困惑的是,为什么我不能像这样直接将 ArrayList 添加到 Jlist:

Whats confusing me is that, why i cannot just add ArrayList to Jlist directly like this :

ArrayList<String> labels = new ArrayList<String>();
JList jlist = new JList(labels);

提前致谢.

推荐答案

包含helper"构造函数的目的是为了使JList 与简单的数据结构更容易使用.

The inclusion of "helper" constructors was meant to make it easier to use the JList with simple data structures.

JList(以及许多 Swing 组件)实际上是为了与向视图提供实际数据的模型一起使用.

The JList (and many Swing components) are actually meant to be used with models that supply the actual data to the view.

原始设计可以追溯到 Swing 并入主库之前(JDK 1.3 之前)和集合 API 引入之前,因此原始开发人员很可能没有 List 对他们可用(因此包含 Vector).

The original design goes way back before Swing was incorporated into the main library (prior to JDK 1.3) and just before the collections API was introduced, so it's likely that the original developers didn't have List available to them (hence the inclusion of Vector).

很可能没有人认为更新库是合适的(部分是因为可能已经决定不应该包含原始构造函数,但我没有参加那次会议;))

It's likely that no one has seen fit to update the libraries since (partially because it may have been decided that the original constructors shouldn't have been included, but I wasn't at that meeting ;))

更好/更简单的解决方案是创建您自己的模型,该模型使用 List 作为数据源.

A better/simpler solution would be to create your own model that uses the List as it's data source.

例如...

public class MyListModel<T> extends AbstractListModel<T> {

    private List<T> people;

    public MyListModel(List<T> people) {
        this.people = people;
    }

    @Override
    public int getSize() {
        return people.size();
    }

    @Override
    public T getElementAt(int index) {
        return people.get(index);
    }
}

然后您可以在需要时简单地将其提供给 JList...

Then you can simply supply it to the JList when ever you need to...

JList myList = new JList(new MyListModel<MyObject>(listOfMyObjets));

这篇关于为什么我不能直接将 ArrayList 添加到 Jlist?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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