1  import javafx.animation.Animation;
  2  import javafx.application.Application;
  3  import javafx.stage.Stage;
  4  import javafx.animation.KeyFrame;
  5  import javafx.animation.Timeline;
  6  import javafx.event.ActionEvent;
  7  import javafx.event.EventHandler;
  8  import javafx.scene.Scene;
  9  import javafx.scene.layout.StackPane;
 10  import javafx.scene.paint.Color;
 11  import javafx.scene.text.Text;
 12  import javafx.util.Duration;
 13  
 14  public class TimelineDemo extends Application {
 15    @Override // Override the start method in the Application class
 16    public void start(Stage primaryStage) {
 17      StackPane pane = new StackPane();
 18      Text text = new Text(20, 50, "Programming is fun");
 19      text.setFill(Color.RED);
 20      pane.getChildren().add(text); // Place text into the stack pane
 21  
 22      // Create a handler for changing text
 23      EventHandler<ActionEvent> eventHandler = e -> {
 24        if (text.getText().length() != 0) {
 25          text.setText("");
 26        }
 27        else {
 28          text.setText("Programming is fun");
 29        }
 30      };
 31      
 32      // Create an animation for alternating text
 33      Timeline animation = new Timeline(
 34        new KeyFrame(Duration.millis(500), eventHandler));
 35      animation.setCycleCount(Timeline.INDEFINITE);
 36      animation.play(); // Start animation
 37  
 38      // Pause and resume animation
 39      text.setOnMouseClicked(e -> {
 40        if (animation.getStatus() == Animation.Status.PAUSED) {
 41          animation.play();
 42        }
 43        else {
 44          animation.pause();
 45        }
 46      });
 47      
 48      // Create a scene and place it in the stage
 49      Scene scene = new Scene(pane, 250, 50);
 50      primaryStage.setTitle("TimelineDemo"); // Set the stage title
 51      primaryStage.setScene(scene); // Place the scene in the stage
 52      primaryStage.show(); // Display the stage
 53    }
 54  
 55    /**
 56     * The main method is only needed for the IDE with limited
 57     * JavaFX support. Not needed for running from the command line.
 58     */
 59    public static void main(String[] args) {
 60      launch(args);
 61    }
 62  }