Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have
Java
JList<myElement> list
which has
Java
listmodel listModel = new DefaultListModel<myElement>()
as its data model. I add my element to listModel dynamically. I want to put each element in alphabetical order when is added to listModel (so my listModel is always sorted!)regarding to what their toString() method is return.

I have try following code, but it remove all the element and add them in alphabetical order.

Java
public void sortList(){
    myElement temp;
    myElement[] ob = new myElement[listModel.getSize()];
    for(int i = 0 ; i <listModel.getSize(); i++ )
        ob[i] = listModel.getElementAt(i);
    int n=ob.length;
    for(int i=0;i<n;i++)
        for(int j=0;j<n-i-1;j++)
        {
            if(ob[j].toString().compareTo(ob[j+1].toString())>0) // used to sort strings
            {
             temp=ob[j];
             ob[j]=ob[j+1];
             ob[j+1]=temp;
            }

          }
    listModel.removeAllElements();
    for(int i=0;i<n;i++)
      listModel.addElement((myElement) ob[i]);
    System.out.println("sort!");

}

also I represent them with jLabel!
Posted

1 solution

Java
Collection list = Collections.list(listModel.elements()); // get a collection of the elements in the model
Collections.sort(list); // sort
listModel.clear(); // remove all elements
for(Object o:list){ listModel.addElement(o); } // add elements


something like that.
You can also extract an Array and sort it via a Comparator[^].

JList should update view automatically.

Have fun!
 
Share this answer
 
Comments
Coder93 6-Aug-14 5:01am    
I don't want to clear listmodel element when new element is added. I want to add each element in its rigth place!
TorstenH. 6-Aug-14 9:54am    
therefor you need to take the elements, create a list of that, sort them, and put them back to where they belong.

There is no way around.

You might use another workaround: Creating a Sorted Component @oracle.com

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900