Swing DefaultListModel question.

S

stroker_ace

Hi,

I am using a DefaultListModel instance to store the contents of a
JList.

The data I want to store in the list is (for implementation reasons)
stored in a TreeSet.

I suspect I may be missing something but I am suprised that there is no
bulk method for adding a whole collection to a DefaultListModel and I
have to use the addElement method to add each object to the
DefaultListModel.

Is there a more elegant method of achieving this?

I could extend DefaultListModel or write a routine to load the objects
but it seems so clumsy.

Cheers for any help.

Lawrie.
 
J

jan V

I suspect I may be missing something but I am suprised that there is no
bulk method for adding a whole collection to a DefaultListModel and I
have to use the addElement method to add each object to the
DefaultListModel.

Is there a more elegant method of achieving this?

I could extend DefaultListModel or write a routine to load the objects
but it seems so clumsy.

In my experience, extending DefaultListModel has been the norm. That way you
can add all kinds of user-friendly constructors to bulk-initialize your
ListModel.
 
R

Roedy Green

I could extend DefaultListModel or write a routine to load the objects
but it seems so clumsy.

DefaultListModel is just a wrapper around Vector using a delegate
Vector object. It uses only the default constructor.

Vector itself has a constructor like this which fairly efficiently
sucks the data out of a collection into an the internal array.:

public Vector(Collection<? extends E> c) {
elementCount = c.size();
// 10% for growth
elementData = new Object[
(int)Math.min((elementCount*110L)/100,Integer.MAX_VALUE)];
c.toArray(elementData);
}

The problem is DefaultListModel.delegate is private. You can't simply
add a constructor that uses this Vector constructor to a subclass of
DefaultListModel. You would have to clone the code in DefaultListModel
adding the constructor.

Unless this turns out to be a bottlenceck, I would not sweat it. you
can use the for:each loop to fairly elegantly plop the elements in
individually.

e.g.

for ( String s : Choices )
{
theListModel.add( s );
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top