Wednesday, June 15, 2016

35. Properties

An IntegerProperty is a javafx beans Property class, which we can attach Listener, or Bind to (as in the next example.)


Two buttons either increment or decrement the integer wrapped by the IntegerProperty. We attach a ChangeListener to this Property. To hold other data variables, we may use StringProperty, DoubleProperty, etc.


package ex35;
 
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
 
public class Ex35 extends Application {
 
    @Override
    public void start(Stage primaryStage) {
 
        IntegerProperty labelNumber 
            = new SimpleIntegerProperty(0);
        
        Button inc = new Button("+");
        inc.setOnAction(e -> 
            labelNumber.set(
                    labelNumber.get()+1
        ));
        
        Button dec = new Button("-");
        dec.setOnAction(e -> 
            labelNumber.set(
                    labelNumber.get()-1
        ));
        
        Label label = new Label("Number: 0");
        
        VBox root = new VBox(inc, dec, label);
        root.setSpacing(50);
        root.setAlignment(Pos.CENTER);
        
        labelNumber.addListener( (ob, oVal, nVal) -> {
            label.setText("Number: " + nVal );
        });
        
        Scene scene = new Scene(root, 400, 400);
        
        primaryStage.setTitle("Example 35. Properties");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

This is the output:


No comments:

Post a Comment