Java Code Examples for javafx.animation.Timeline#setCycleCount()

The following examples show how to use javafx.animation.Timeline#setCycleCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AutoScrollingWindow.java    From graph-editor with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Starts the auto-scrolling.
 */
private void startScrolling() {

    isScrolling = true;
    jumpsTaken = 0;

    final KeyFrame frame = new KeyFrame(Duration.millis(parameters.getJumpPeriod()), event -> {
        if (dragEventTarget != null && isScrolling && jumpDistance != null) {
            panBy(jumpDistance.getX(), jumpDistance.getY());
            dragEventTarget.fireEvent(currentDragEvent);
            jumpsTaken++;
        }
    });

    timeline = new Timeline();
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.getKeyFrames().add(frame);
    timeline.play();
}
 
Example 2
Source File: ChartLayoutAnimator.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
/**
 * Play a animation containing the given keyframes.
 *
 * @param keyFrames The keyframes to animate
 * @return A id reference to the animation that can be used to stop the animation if needed
 */
public Object animate(KeyFrame... keyFrames) {
    Timeline t = new Timeline();
    t.setAutoReverse(false);
    t.setCycleCount(1);
    t.getKeyFrames().addAll(keyFrames);
    t.setOnFinished(this);
    // start animation timer if needed
    if (activeTimeLines.isEmpty())
        start();
    // get id and add to map
    activeTimeLines.put(t, t);
    // play animation
    t.play();
    return t;
}
 
Example 3
Source File: MainScene.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates and starts the earth timer
 */
public void startEarthTimer() {
	// Set up earth time text update
	timeLabeltimer = new Timeline(new KeyFrame(Duration.millis(TIME_DELAY), ae -> updateTimeLabels()));
	// Note: Infinite Timeline might result in a memory leak if not stopped
	// properly.
	// All the objects with animated properties would not be garbage collected.
	timeLabeltimer.setCycleCount(javafx.animation.Animation.INDEFINITE);
	timeLabeltimer.play();

}
 
Example 4
Source File: CarPane.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
/** Construct and animate a default CarPane */
CarPane() {
	drawCar();
	animation = new Timeline(
		new KeyFrame(Duration.millis(50), e -> moveCar()));
	animation.setCycleCount(Timeline.INDEFINITE);
}
 
Example 5
Source File: ClockPane.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
/** Construct a click with specified hour, minute, and second */
public ClockPane(int hour, int minute, int second) {
	this.hour = hour;
	this.minute = minute;
	this.second = second;
	paintClock();
	animation = new Timeline(
		new KeyFrame(Duration.millis(1000), e -> moveClock()));
	animation.setCycleCount(Timeline.INDEFINITE);
	animation.play();
}
 
Example 6
Source File: FanPane.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
/**  Construct a FanPane */
public FanPane() {
	setPadding(new Insets(10, 10, 10, 10));
	circle.setStroke(Color.BLACK);
	circle.setFill(Color.WHITE);
	circle.centerXProperty().bind(widthProperty().divide(2));
	circle.centerYProperty().bind(heightProperty().divide(2));
	circle.radiusProperty().bind((heightProperty().divide(2)).multiply(.90));
	getBlades();
	getChildren().addAll(circle, paneForBlades);
	fan = new Timeline(
		new KeyFrame(Duration.millis(50), e -> spinFan()));
	fan.setCycleCount(Timeline.INDEFINITE);
	fan.play(); // Start animation
}
 
Example 7
Source File: SystemClipboard.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public SystemClipboard() {
    clipboard = Clipboard.getSystemClipboard();
    Timeline monitorTask = new Timeline(new KeyFrame(Duration.millis(200), this));
    monitorTask.setCycleCount(Animation.INDEFINITE);
    monitorTask.play();
    prevData = null;
}
 
Example 8
Source File: TimelineSample.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public TimelineSample() {
    super(280,120);

    //create a circle
    final Circle circle = new Circle(25,25, 20,  Color.web("1c89f4"));
    circle.setEffect(new Lighting());

    //create a timeline for moving the circle
    timeline = new Timeline();        
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.setAutoReverse(true);

    //one can start/pause/stop/play animation by
    //timeline.play();
    //timeline.pause();
    //timeline.stop();
    //timeline.playFromStart();
    
    //add the following keyframes to the timeline
    timeline.getKeyFrames().addAll
        (new KeyFrame(Duration.ZERO,
                      new KeyValue(circle.translateXProperty(), 0)),
         new KeyFrame(new Duration(4000),
                      new KeyValue(circle.translateXProperty(), 205)));


    getChildren().add(createNavigation());
    getChildren().add(circle);
    // REMOVE ME
    setControls(
            new SimplePropertySheet.PropDesc("Timeline rate", timeline.rateProperty(), -4d, 4d)
            //TODO it is possible to do it for integer?
    );
    // END REMOVE ME
}
 
Example 9
Source File: AnimationHelper.java    From ApkToolPlus with Apache License 2.0 5 votes vote down vote up
/**
     * 抖动窗口
     *
     * @param window 窗口对象
     * @param count 抖动次数
     */
    public static void shake(Window window, int count) {

        final Delta detla = new Delta();
        detla.x = 0;
        detla.y = 0;

        Timeline timelineX = new Timeline(new KeyFrame(Duration.seconds(0.1), event -> {
            if (detla.x == 0) {
                window.setX(window.getX() + 10);
                detla.x = 1;
            } else {
                window.setX(window.getX() - 10);
                detla.x = 0;
            }
        }));

        //timelineX.setCycleCount(Timeline.INDEFINITE);
        timelineX.setCycleCount(count);
        timelineX.setAutoReverse(false);
        timelineX.play();

//        Timeline timelineY = new Timeline(new KeyFrame(Duration.seconds(0.1), event -> {
//            if (detla.y == 0) {
//                stage.setY(stage.getY() + 10);
//                detla.y = 1;
//            } else {
//                stage.setY(stage.getY() - 10);
//                detla.y = 0;
//            }
//        }));
//
//        timelineY.setCycleCount(count);
//        timelineY.setAutoReverse(false);
//        timelineY.play();
    }
 
Example 10
Source File: DaoLaunchWindow.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void startAutoSectionChange() {
    autoPlayTimeline = new Timeline(new KeyFrame(
            Duration.seconds(10),
            ae -> goToNextSection()
    ));
    autoPlayTimeline.setCycleCount(Animation.INDEFINITE);

    autoPlayTimeline.play();
}
 
Example 11
Source File: MonitorController.java    From arcgis-runtime-demo-java with Apache License 2.0 5 votes vote down vote up
private void dispatchHelicopter() {
  // create an animation timer
  Timeline animator = new Timeline();
  animator.setCycleCount(Animation.INDEFINITE);

  // specify units
  LinearUnit meters = new LinearUnit(LinearUnitId.METERS);
  AngularUnit degrees = new AngularUnit(AngularUnitId.DEGREES);

  animator.getKeyFrames().add(new KeyFrame(Duration.millis(100), actionEvent -> {
    // get the geodesic distance
    GeodesicDistanceResult distance = GeometryEngine.distanceGeodesic((Point) helicopter.getGeometry(), fireLocation,
        meters, degrees, GeodeticCurveType.GEODESIC);

    if (distance.getDistance() > 40) {
      // move helicopter 10 meters towards target
      Point newPosition = GeometryEngine.moveGeodesic((Point) helicopter.getGeometry(), 40, meters, distance
          .getAzimuth1(), degrees, GeodeticCurveType.GEODESIC);
      helicopter.setGeometry(newPosition);
    } else {
      animator.stop();
      helicopterButton.setDisable(true);
      flagButton.setDisable(false);
    }
  }));
  animator.play();
}
 
Example 12
Source File: CameraController.java    From FXyzLib with GNU General Public License v3.0 5 votes vote down vote up
public CameraController(boolean enableTransforms, AnimationPreference movementType) {
    enable = enableTransforms;
    animPref = movementType;
    switch (animPref) {
        case TIMELINE:
            timeline = new Timeline();
            timeline.setCycleCount(Animation.INDEFINITE);
            break;
        case TIMER:
            timer = new AnimationTimer() {
                @Override
                public void handle(long l) {
                    if (enable) {
                        initialize();
                        enable = false;
                    }
                    update();
                }
            };
            break;
        case TRANSITION:
            transition = new Transition() {
                {setCycleDuration(Duration.seconds(1));}
                @Override
                protected void interpolate(double frac) {
                    updateTransition(frac);
                }
            };
            transition.setCycleCount(Animation.INDEFINITE);
            break;
        case ANIMATION:
            
            break;
    }

}
 
Example 13
Source File: Exercise_16_21.java    From Intro-to-Java-Programming with MIT License 5 votes vote down vote up
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
	// Set text field properties
	count.setAlignment(Pos.CENTER);
	count.setFont(Font.font(60));
	count.setPrefColumnCount(4);
	
	// Set meidaplayer to loop
	mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);

	// Create a pane
	StackPane pane = new StackPane(count);

	// Create animation for stopwatch
	animation = new Timeline(
		new KeyFrame(Duration.millis(1000), e -> run()));
	animation.setCycleCount(Timeline.INDEFINITE);

	count.setOnKeyPressed(e -> {
		if (e.getCode() == KeyCode.ENTER) {
			animation.play();
		}
	});

	// Create a scene and place it in the stage
	Scene scene = new Scene(pane);
	primaryStage.setTitle("Exercise_16_21"); // Set the Stage title
	primaryStage.setScene(scene); // Place the scene in the stage
	primaryStage.show(); // Display the stage
}
 
Example 14
Source File: BouncingTargets.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
private void startExercise() {
	super.showTextOnFeed("Score: 0");

	addTargets(shootTargets, "targets/shoot_dont_shoot/shoot.target", shootCount);
	addTargets(dontShootTargets, "targets/shoot_dont_shoot/dont_shoot.target", dontShootCount);

	targetAnimation = new Timeline(new KeyFrame(Duration.millis(20), e -> updateTargets()));
	targetAnimation.setCycleCount(Timeline.INDEFINITE);
	targetAnimation.play();
}
 
Example 15
Source File: Controller.java    From game-of-life-java with MIT License 5 votes vote down vote up
@FXML
private void onRun(Event evt) {
    toggleButtons(false);

    loop = new Timeline(new KeyFrame(Duration.millis(300), e -> {
        board.update();
        display.displayBoard(board);
    }));

    loop.setCycleCount(100);
    loop.play();
}
 
Example 16
Source File: Board.java    From Game2048FX with GNU General Public License v3.0 4 votes vote down vote up
private void createScore() {
    Label lblTitle = new Label("2048");
    lblTitle.getStyleClass().addAll("game-label", "game-title");
    Label lblSubtitle = new Label("FX");
    lblSubtitle.getStyleClass().addAll("game-label", "game-subtitle");
    HBox hFill = new HBox();
    HBox.setHgrow(hFill, Priority.ALWAYS);
    hFill.setAlignment(Pos.CENTER);

    VBox vScores = new VBox();
    HBox hScores = new HBox(5);

    vScore.setAlignment(Pos.CENTER);
    vScore.getStyleClass().add("game-vbox");
    Label lblTit = new Label("SCORE");
    lblTit.getStyleClass().addAll("game-label", "game-titScore");
    lblScore.getStyleClass().addAll("game-label", "game-score");
    lblScore.textProperty().bind(gameScore.asString());
    vScore.getChildren().addAll(lblTit, lblScore);

    VBox vRecord = new VBox(-5);
    vRecord.setAlignment(Pos.CENTER);
    vRecord.getStyleClass().add("game-vbox");
    Label lblTitBest = new Label("BEST");
    lblTitBest.getStyleClass().addAll("game-label", "game-titScore");
    lblBest.getStyleClass().addAll("game-label", "game-score");
    lblBest.textProperty().bind(gameBest.asString());
    vRecord.getChildren().addAll(lblTitBest, lblBest);
    hScores.getChildren().addAll(vScore, vRecord);
    VBox vFill = new VBox();
    VBox.setVgrow(vFill, Priority.ALWAYS);
    vScores.getChildren().addAll(hScores, vFill);

    hTop.getChildren().addAll(lblTitle, lblSubtitle, hFill, vScores);
    hTop.setMinSize(gridWidth, TOP_HEIGHT);
    hTop.setPrefSize(gridWidth, TOP_HEIGHT);
    hTop.setMaxSize(gridWidth, TOP_HEIGHT);

    vGame.getChildren().add(hTop);

    HBox hTime = new HBox();
    hTime.setMinSize(gridWidth, GAP_HEIGHT);
    hTime.setAlignment(Pos.BOTTOM_CENTER);

    lblMode.getStyleClass().addAll("game-label", "game-time");

    lblTime.getStyleClass().addAll("game-label", "game-time");
    lblTime.textProperty().bind(clock);
    HBox hGap = new HBox();
    HBox.setHgrow(hGap, Priority.ALWAYS);
    timer = new Timeline(new KeyFrame(Duration.ZERO, e -> {
        clock.set(LocalTime.now().minusNanos(time.toNanoOfDay()).format(fmt));
    }), new KeyFrame(Duration.seconds(1)));
    timer.setCycleCount(Animation.INDEFINITE);
    hTime.getChildren().addAll(lblMode, hGap, lblTime);

    vGame.getChildren().add(hTime);
    getChildren().add(vGame);

    lblPoints.getStyleClass().addAll("game-label", "game-points");
    lblPoints.setAlignment(Pos.CENTER);
    lblPoints.setMinWidth(100);
    getChildren().add(lblPoints);
}
 
Example 17
Source File: Exercise_16_23.java    From Intro-to-Java-Programming with MIT License 4 votes vote down vote up
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
	final int COLUMN_COUNT = 27;
	tfSpeed.setPrefColumnCount(COLUMN_COUNT);
	tfPrefix.setPrefColumnCount(COLUMN_COUNT);
	tfNumberOfImages.setPrefColumnCount(COLUMN_COUNT);
	tfURL.setPrefColumnCount(COLUMN_COUNT);

	// Create a button
	Button btStart = new Button("Start Animation");

	// Create a grid pane for labels and text fields
	GridPane paneForInfo = new GridPane();
	paneForInfo.setAlignment(Pos.CENTER);
	paneForInfo.add(new Label("Enter information for animation"), 0, 0);
	paneForInfo.add(new Label("Animation speed in milliseconds"), 0, 1);
	paneForInfo.add(tfSpeed, 1, 1);
	paneForInfo.add(new Label("Image file prefix"), 0, 2);
	paneForInfo.add(tfPrefix, 1, 2);
	paneForInfo.add(new Label("Number of images"), 0, 3);
	paneForInfo.add(tfNumberOfImages, 1, 3);
	paneForInfo.add(new Label("Audio file URL"), 0, 4);
	paneForInfo.add(tfURL, 1, 4);


	// Create a border pane
	BorderPane pane = new BorderPane();
	pane.setBottom(paneForInfo);
	pane.setCenter(paneForImage);
	pane.setTop(btStart);
	pane.setAlignment(btStart, Pos.TOP_RIGHT);

	// Create animation
	animation = new Timeline(
		new KeyFrame(Duration.millis(1000), e -> nextImage()));
	animation.setCycleCount(Timeline.INDEFINITE);

	// Create and register the handler
	btStart.setOnAction(e -> {
		if (tfURL.getText().length() > 0) {
			MediaPlayer mediaPlayer = new MediaPlayer(
				new Media(tfURL.getText()));
			mediaPlayer.play();
		}
		if (tfSpeed.getText().length() > 0)
			animation.setRate(Integer.parseInt(tfSpeed.getText()));
		animation.play();
	});

	// Create a scene and place it in the stage
	Scene scene = new Scene(pane, 550, 680);
	primaryStage.setTitle("Exercise_16_23"); // Set the stage title
	primaryStage.setScene(scene); // Place the scene in the stage
	primaryStage.show(); // Display the stage
}
 
Example 18
Source File: Splash.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void initTimeline() {
    timeline = new Timeline();
    timeline.setCycleCount(Timeline.INDEFINITE);
    KeyFrame kf = new KeyFrame(Config.ANIMATION_TIME, new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) {
            if (state == STATE_SHOW_TITLE) {
                stateArg++;
                int center = Config.SCREEN_WIDTH / 2;
                int offset = (int)(Math.cos(stateArg / 4.0) * (40 - stateArg) / 40 * center);
                brick.setTranslateX(center - brick.getImage().getWidth() / 2 + offset);
                breaker.setTranslateX(center - breaker.getImage().getWidth() / 2 - offset);
                if (stateArg == 40) {
                    stateArg = 0;
                    state = STATE_SHOW_STRIKE;
                }
                return;
            }
            if (state == STATE_SHOW_STRIKE) {
                if (stateArg == 0) {
                    strike.setTranslateX(breaker.getTranslateX() + brick.getImage().getWidth());
                    strike.setScaleX(0);
                    strike.setScaleY(0);
                    strike.setVisible(true);
                }
                stateArg++;
                double coef = stateArg / 30f;
                brick.setTranslateX(breaker.getTranslateX() +
                    (breaker.getImage().getWidth() - brick.getImage().getWidth()) / 2f * (1 - coef));
                strike.setScaleX(coef);
                strike.setScaleY(coef);
                strike.setRotate((30 - stateArg) * 2);
                if (stateArg == 30) {
                    stateArg = 0;
                    state = STATE_SUN;
                }
                return;
            }
            // Here state == STATE_SUN
            if (pressanykey.getOpacity() < 1) {
                pressanykey.setOpacity(pressanykey.getOpacity() + 0.05f);
            }
            stateArg--;
            double x = SUN_AMPLITUDE_X * Math.cos(stateArg / 100.0);
            double y = SUN_AMPLITUDE_Y * Math.sin(stateArg / 100.0);
            if (y < 0) {
                for (Node node : NODES_SHADOWS) {
                    // Workaround RT-1976
                    node.setTranslateX(-1000);
                }
                return;
            }
            double sunX = Config.SCREEN_WIDTH / 2 + x;
            double sunY = Config.SCREEN_HEIGHT / 2 - y;
            sun.setTranslateX(sunX - sun.getImage().getWidth() / 2);
            sun.setTranslateY(sunY - sun.getImage().getHeight() / 2);
            sun.setRotate(-stateArg);
            for (int i = 0; i < NODES.length; i++) {
                NODES_SHADOWS[i].setOpacity(y / SUN_AMPLITUDE_Y / 2);
                NODES_SHADOWS[i].setTranslateX(NODES[i].getTranslateX() +
                    (NODES[i].getTranslateX() + NODES[i].getImage().getWidth() / 2 - sunX) / 20);
                NODES_SHADOWS[i].setTranslateY(NODES[i].getTranslateY() +
                    (NODES[i].getTranslateY() + NODES[i].getImage().getHeight() / 2 - sunY) / 20);
            }
        }
    });
    timeline.getKeyFrames().add(kf);
}
 
Example 19
Source File: TimelineEventsSample.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
public TimelineEventsSample() {
    super(70,70);
    //create a circle with effect
    final Circle circle = new Circle(20,  Color.rgb(156,216,255));
    circle.setEffect(new Lighting());
    //create a text inside a circle
    final Text text = new Text (i.toString());
    text.setStroke(Color.BLACK);
    //create a layout for circle with text inside
    final StackPane stack = new StackPane();
    stack.getChildren().addAll(circle, text);
    stack.setLayoutX(30);
    stack.setLayoutY(30);

    //create a timeline for moving the circle

    timeline = new Timeline();
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.setAutoReverse(true);

    //one can add a specific action when each frame is started. There are one or more frames during
    // executing one KeyFrame depending on set Interpolator.
    timer = new AnimationTimer() {
        @Override
        public void handle(long l) {
            text.setText(i.toString());
            i++;
        }

    };

    //create a keyValue with factory: scaling the circle 2times
    KeyValue keyValueX = new KeyValue(stack.scaleXProperty(), 2);
    KeyValue keyValueY = new KeyValue(stack.scaleYProperty(), 2);

    //create a keyFrame, the keyValue is reached at time 2s
    Duration duration = Duration.seconds(2);
    //one can add a specific action when the keyframe is reached
    EventHandler<ActionEvent> onFinished = new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
             stack.setTranslateX(java.lang.Math.random()*200-100);
             //reset counter
             i = 0;
        }
    };

    KeyFrame keyFrame = new KeyFrame(duration, onFinished , keyValueX, keyValueY);

    //add the keyframe to the timeline
    timeline.getKeyFrames().add(keyFrame);

    getChildren().add(stack);
}
 
Example 20
Source File: Example3T.java    From Introduction-to-JavaFX-for-Game-Development with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void start(Stage theStage) 
{
    theStage.setTitle( "Timeline Example" );
    
    Group root = new Group();
    Scene theScene = new Scene( root );
    theStage.setScene( theScene );
    
    Canvas canvas = new Canvas( 512, 512 );
    root.getChildren().add( canvas );
    
    GraphicsContext gc = canvas.getGraphicsContext2D();
    
    Image earth = new Image( "earth.png" );
    Image sun   = new Image( "sun.png" );
    Image space = new Image( "space.png" );
    
    Timeline gameLoop = new Timeline();
    gameLoop.setCycleCount( Timeline.INDEFINITE );
    
    final long timeStart = System.currentTimeMillis();
    
    KeyFrame kf = new KeyFrame(
        Duration.seconds(0.017),                // 60 FPS
        new EventHandler<ActionEvent>()
        {
            public void handle(ActionEvent ae)
            {
                double t = (System.currentTimeMillis() - timeStart) / 1000.0; 
                            
                double x = 232 + 128 * Math.cos(t);
                double y = 232 + 128 * Math.sin(t);
                
                // Clear the canvas
                gc.clearRect(0, 0, 512,512);
                
                // background image clears canvas
                gc.drawImage( space, 0, 0 );
                gc.drawImage( earth, x, y );
                gc.drawImage( sun, 196, 196 );
            }
        });
    
    gameLoop.getKeyFrames().add( kf );
    gameLoop.play();
    
    theStage.show();
}