Ryzal Yusoff
Ryzal Yusoff

Reputation: 1047

Why I cannot add ArrayList directly to 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());

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

thanks in advance.

Upvotes: 1

Views: 4677

Answers (4)

MadProgrammer
MadProgrammer

Reputation: 347204

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

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

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.

For example...

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

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

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

Upvotes: 7

nachokk
nachokk

Reputation: 14413

It's simple. JList constructors don't expect ArrayList

JList()
Constructs a JList with an empty, read-only, model.
JList(E[] listData)
Constructs a JList that displays the elements in the specified array.
JList(ListModel<E> dataModel)
Constructs a JList that displays elements from the specified, non-null, model.
JList(Vector<? extends E> listData)
Constructs a JList that displays the elements in the specified Vector.

Upvotes: 2

tckmn
tckmn

Reputation: 59283

Because JList doesn't have a constructor that accepts an ArrayList (or a List). It can only accept an array, a ListModel, or a Vector. See the documentation.

An ArrayList is not an array. You can't pass an ArrayList to a method that wants an array.

Upvotes: 2

Reimeus
Reimeus

Reputation: 159784

JList has no constructor that accepts a List. The first example works as it uses the constructor JList(Object[]).

Familiarize yourself with the javadoc

Upvotes: 3

Related Questions