Wednesday, June 15, 2016

36. Binding

The only difference from last example is now we bind the label text property (destination) to our IntegerProperty (the source).


Again the buttons change the integer contained in the IntegerProperty by either incrementing, or decrementing.


package ex36;
 
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 Ex36 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);
        
        label.textProperty()
                .bind(labelNumber.asString());
        Scene scene = new Scene(root, 400, 400);
        
        primaryStage.setTitle("Example 36. Binding");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

This is the output:


No comments:

Post a Comment