Saturday, June 4, 2016

27. AnimationTimer

Once an AnimationTimer object is started, it will execute its handler method every frame. Here we have a timer operation, initiated by clicking the 'Start' button.


Had we not cast it to int, it would display whenever it executes. It is easy to see this by removing the (int) cast.


package ex27;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class Ex27 extends Application {

    long startTime;
    AnimationTimer animationTimer;
    
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Example 27. AnimationTimer");
        
        Label label = new Label("  Time: 0");
        label.setFont(new Font("Georgia", 72));
        
        animationTimer = new AnimationTimer() {
            @Override
            public void handle(long currentTime) {
                double t = (currentTime - startTime) / 1000000000;
                label.setText("  Time: " + (int)t);
            }
        };
        
        Button start = new Button("Start");
        Button stop = new Button("Stop");
        start.setOnAction(e -> startTimer());
        stop.setOnAction(e -> stopTimer());
        HBox buttons = new HBox(100);
        buttons.getChildren().addAll(start, stop);
        
        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20));
        layout.getChildren().addAll(label, buttons);
        Scene scene = new Scene(layout, 500, 200);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    public void startTimer() {
        startTime = System.nanoTime();
        animationTimer.start();
    }
    
    public void stopTimer() {
        animationTimer.stop();
    }
}

This is the output at a certain time after 'Start' button was clicked:


No comments:

Post a Comment