Monday, May 7, 2012

JavaFX Binding, sync between UI component - display slider property

Last article we have a stand alone slider only. It's modified to bind with a Text, such that the text will be updated when the slider value changed.



package javafxui;

import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Group;
import javafx.scene.GroupBuilder;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.control.SliderBuilder;
import javafx.scene.control.Tooltip;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Slider extends Application {
    
    int defaultSliderValue = 10;
    IntegerProperty sliderValue = new SimpleIntegerProperty(defaultSliderValue);

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();

        Slider slider = SliderBuilder.create()
                .layoutX(50)
                .layoutY(50)
                .prefWidth(400)
                .min(0)
                .max(100)
                .majorTickUnit(20)
                .minorTickCount(3)
                .showTickMarks(true)
                .showTickLabels(true)
                .tooltip(new Tooltip("Slider Tooltip"))
                .build();
        
        Text slidertext = TextBuilder.create()
                .layoutX(50)
                .layoutY(100)
                .fill(Color.RED)
                .font(Font.font("SansSerif", FontWeight.BOLD, 20))
                .build();
        
        Group myGroup = GroupBuilder.create()
                .children(slider, slidertext)
                .build();
        
        root.getChildren().add(myGroup);
        
        slider.valueProperty().bindBidirectional(sliderValue);
        slidertext.textProperty().bind(sliderValue.asString());
  
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }
}


No comments:

Post a Comment