Sorting

The list returned from the getChildren method of the org.zkoss.zk.ui.Component interface is live. So is the getItems method of the org.zkoss.zul.Listbox interface and others. In other words, you can manipulate it content directly. For example, the following statements are equivalent:

comp.getChildren().remove(0);
((Component)comp.getChildren().get(0)).setParent(null);

However, you cannot use the sort method of the java.util.Collections class to sort them. The reason is subtle: the list of children automatically removes a child from the original position, when you add it to another position. For example, the following statement actually moves the second child in front of the first child.

comp.getChildren().add(0, comp.getChildren().get(1));

It behaves differently from a normal list (such as LinkedList), so the sort method of Collections won't work.

To simplify the sorting of components, we therefore provide the sort method in the org.zkoss.zk.ui.Components class that works with the list of children.

In the following example, we utilize the sort method and the org.zkoss.zul.ListitemComparator to provide the sorting for a list box.

Notice that this is only for illustration because list boxes support sorting of list items directly. Refer to the Sorting subsection of the List Boxes section in the ZUML with the XUL Component Set chapter.

<window title="Sort Listbox" border="normal" width="200px">
    <vbox>    
        <listbox id="l">        
            <listhead>            
                <listheader label="name"/>                
                <listheader label="gender"/>                
            </listhead>            
            <listitem>            
                <listcell label="Mary"/>                
                <listcell label="FEMALE"/>                
            </listitem>            
            <listitem>            
                <listcell label="John"/>                
                <listcell label="MALE"/>                
            </listitem>            
            <listitem>            
                <listcell label="Jane"/>                
                <listcell label="FEMALE"/>                
            </listitem>            
            <listitem>            
                <listcell label="Henry"/>                
                <listcell label="MALE"/>                
            </listitem>            
        </listbox>        
        <hbox>        
            <button label="Sort 1" onClick="sort(l, 0)"/>            
            <button label="Sort 2" onClick="sort(l, 1)"/>            
        </hbox>        
    </vbox>    
    <zscript>    
    void sort(Listbox l, int j) {    
        Components.sort(l.getItems(), new ListitemComparator(j));        
    }    
    </zscript>    
</window>