且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能直接添加到ArrayList中JList的?

更新时间:2022-02-17 01:37:32

的帮手构造列入是为了更容易地使用 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.

最初的设计变回来的路上前秋千被纳入主库(早于JDK 1.3),并引入了集合API之前,所以它很可能是原开发商没有列表提供给他们(因此列入向量)。

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

有一个更好/更简单的解决方案是创建一个使用列出您自己的模型,因为它的数据源。

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的当过你需要...

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