Saturday, June 4, 2016

29. Slider controlling Progress

A slider is used to control the value of the progress bar and progress indicator.


A listener is attached to the slider value to set the progress values, whenever it changes. Note the cast to double since new_val is a Number object.


package ex29;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.Slider;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Ex29  extends Application {

    @Override
    public void start(Stage stage) {
        GridPane root = new GridPane();
        root.setVgap(10);
        root.setHgap(10);
        root.setAlignment(Pos.CENTER);
        
        Label lab1 = new Label();
        lab1.setText("progress slider:");
        GridPane.setConstraints(lab1, 0, 0);
        
        Slider slider = new Slider(0,1,0.5);
        slider.setBlockIncrement(0.01);
        slider.setShowTickMarks(true);
        slider.setShowTickLabels(true);
        slider.setMajorTickUnit(0.2);
        GridPane.setConstraints(slider, 1, 0);
        
        Label lab2 = new Label();
        lab2.setText("Progress Bar");
        GridPane.setConstraints(lab2, 0, 1);
 
        ProgressBar prBar = new ProgressBar(0.5);
        GridPane.setConstraints(prBar, 1, 1);
        
        Label lab3 = new Label();
        lab3.setText("Progress Indicator");
        GridPane.setConstraints(lab3, 0, 2);
 
        ProgressIndicator prInd = new ProgressIndicator(0.5);
        GridPane.setConstraints(prInd, 1, 2);
        
        slider.valueProperty().addListener((ov, old_val, new_val) -> {
            prBar.setProgress((double)new_val);
            prInd.setProgress((double)new_val);
        });
        root.getChildren().addAll(lab1, slider, lab2, prBar, lab3, prInd);
        Scene scene = new Scene(root, 400, 200);
        stage.setScene(scene);
        stage.setTitle("Example 29. Slider controlling Progress");
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

This is the output after changing the slider value:


No comments:

Post a Comment