Skip to content

Sample 019

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

import org.beanfabrics.model.AbstractPM;
import org.beanfabrics.model.DecimalPM;
import org.beanfabrics.model.PMManager;
import org.beanfabrics.support.OnChange;

/**
 * This sample demonstrates some features of the @OnChange annotation.
 * <p>
 * Q: how can I change the value of some property dependent on the value of some other property?
 * <p>
 * A: Use the @OnChange annotation.
 */
public class Sample019 {
    static class AreaCalculatorPM extends AbstractPM {
        DecimalPM length = new DecimalPM();
        DecimalPM width = new DecimalPM();
        DecimalPM area = new DecimalPM();
        
        public AreaCalculatorPM() {
            length.setMandatory(true);
            width.setMandatory(true);
            area.setEditable(false);
            PMManager.setup(this);
        }
        
        @OnChange(path={"length","width"})
        public void calculateArea() {
            if ( length.isValid() && width.isValid()) {
                area.setDouble( length.getDouble()*width.getDouble());
            } else {
                area.setText("");
            }
        }
    }
    
    
    public static void main(String[] args) {
        // Create the model
        AreaCalculatorPM model = new AreaCalculatorPM();
        
        // 1st test
        model.length.setDouble(3.0);
        model.width.setDouble(4.0);
        // "area" should be "12"
        System.out.println("1: model.area.getText()='"+model.area.getText()+"'");
        
        // 2nd test
        model.length.setText("some text");
        model.width.setDouble(4.0);
        // "area" should be "" since "length" is invalid
        System.out.println("2: model.area.getText()='"+model.area.getText()+"'");
    }
    
}