• Post Reply Bookmark Topic Watch Topic
  • New Topic

arraylist and DefaultListModel  RSS feed

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess I'm doing some inefficient coding here and wonder if someone can assist:

I�m using DefaultListModel and I need to sort it. The sorting is with a comparable class (it works fine) that problem is this:

Collections.sort(defaultListModel,comp); //this is invalid because defaultListModel is not a list.

What I�m doing is converting the model to arrayList like:

ArrayList al = new ArrayList();
For (int x=0; x<defaultListModel.size(); x++)
{
MyObject mo = (MyObject) defaultListModel.elementAt(x);
al.add(mo)

}

And then I take it to the collection and then I reverse everything to the model (ahhhh)

Is there a better way to do that?
[ July 21, 2008: Message edited by: Bear Bibeault ]
 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally I prefer to use methods that already exist, rather than writing my own code. So I looked in the API documentation and found some useful-looking methods:I don't know if you have to call the fireContentsChanged() method after that; I would leave that out unless it becomes apparent that you need it.
 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
elegant. thanks
 
Quiddo Quitch
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that would be elegant...if only it worked.

According the javadocs, DefaultListModel.copyInto(Object[] anArray) copies the contents of the DefaultListModel into anArray, not the other way around.

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/DefaultListModel.html#copyInto(java.lang.Object[])

I find it idiotic that there is no way to create a listModel using an ArrayList/Vector/Array as an argument, besides providing it to the JList constructor.

If i'm missing something, please enlighten me.
 
Campbell Ritchie
Marshal
Posts: 56581
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tried subclassing DefaultListModel and organising a setListData(java.util.List dataList) method?

Don't know whether it would work.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!