Skip to content

Sample 002

Michael Karneim edited this page May 9, 2018 · 1 revision
package wiki.snippets;

import java.util.Collection;

import org.beanfabrics.Path;
import org.beanfabrics.model.AbstractPM;
import org.beanfabrics.model.IntegerPM;
import org.beanfabrics.model.ListPM;
import org.beanfabrics.model.TextPM;
import org.beanfabrics.model.PMManager;

/**
 * Demonstration of some features of the {@link ListPM}.
 *
 */
public class Sample002 {
    /**
     * Simple model for a list element
     */
    private static class ElementPM extends AbstractPM {
        TextPM name = new TextPM();
        IntegerPM initialPosition = new IntegerPM();
        
        public ElementPM(String name, int pos) {
            PMManager.setup(this);
            this.name.setText(name);
            this.initialPosition.setInteger(pos);
        }
    }
    
    
    public static void main(String[] args) {
        String[] fruits = new String[] {"Apple","Orange","Banana","Pineapple","Peach","Cherry"};
        
        // create new empty list
        ListPM<ElementPM> list = new ListPM<ElementPM>();
        // populate list
        for( int i=0; i<fruits.length; ++i) {
            list.add( new ElementPM(fruits[i], i));
        }
        print( "start", list);
        
        // sort list contents by "name"
        list.sortBy(/*ascending=*/true, new Path("name"));
        print( "sorted by name", list);
        
        // select first 3 elements
        list.getSelection().setInterval(0, 2);
        print( "selected first 3 elements", list);
        
        // sort list contents by "initialPosition"
        list.sortBy(true, new Path("initialPosition"));
        print( "sorted by initialPosition", list);
        
        // copy selection
        Collection<ElementPM> copyOfSelection = list.getSelection().toCollection();
        
        // remove selected elements
        list.removeAll( list.getSelection());
        print( "removed selection", list);
        
        // add removed elements (to the end) again
        list.addAll( copyOfSelection);
        print( "added old selection to end", list);
        
        // select old selection
        list.getSelection().addAll(copyOfSelection);
        print( "selected old selection", list);
        
    }

    /**
     * Prints out the elements of the specified list.
     * @param header the header of the printout
     * @param list
     */
    private static void print(String header, ListPM<ElementPM> list) {
        System.out.println(header);
        for( ElementPM cell: list) {
            boolean isSelected = list.getSelection().contains(cell);
            char selectionMark = isSelected?'#':' ';
            System.out.println( selectionMark+cell.initialPosition.getText()+"\t"+cell.name.getText());
        }
        System.out.println();
    }
}
Clone this wiki locally