4

I'm looking to make a label blink in and out ever 0.1 seconds in javafx. The text appears on top of an ImageView gif that is running in the background. How would I go about doing this or if you have any suggestions on the best method?

Thanks

2 Answers2

10

@fabian's solution is nice. Nevertheless, in this case, you could use a FadeTransition. It alters the opacity of the node and is a good fit for your use-case.

FadeTransition fadeTransition = new FadeTransition(Duration.seconds(0.1), label);
fadeTransition.setFromValue(1.0);
fadeTransition.setToValue(0.0);
fadeTransition.setCycleCount(Animation.INDEFINITE);

MCVE

import javafx.animation.Animation;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

public class LabelBlink extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Label label = new Label("Blink");
        FadeTransition fadeTransition = new FadeTransition(Duration.seconds(0.1), label);
        fadeTransition.setFromValue(1.0);
        fadeTransition.setToValue(0.0);
        fadeTransition.setCycleCount(Animation.INDEFINITE);
        fadeTransition.play();
        Scene scene = new Scene(new StackPane(label));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch();
    }
}
ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176
7

Use a timeline:

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.05), evt -> label.setVisible(false)),
                                 new KeyFrame(Duration.seconds( 0.1), evt -> label.setVisible(true)));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
fabian
  • 80,457
  • 12
  • 86
  • 114