问题
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.
回答1:
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));
回答2:
JList
has no constructor that accepts a List
. The first example works as it uses the constructor JList(Object[]).
Familiarize yourself with the javadoc
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/17226489/why-i-cannot-add-arraylist-directly-to-jlist