Search code examples
javabuttonjavafxsleeppause

Java, how to make a pause in JavaFX


I have 4 buttons and I wanna make them blink. I need a pause for that purpose. How can I simply pause for like 500ms after each iteration? Is it possible to do it without threads?

public void blink() {
        Button[] btn = new Button[]{btn1, btn2, btn3, btn4};
        Random rn = new Random();

        for (int i = 0; i < 100; i++) {
            int d = rn.nextInt(4) + 1;
            new Timeline(
                    new KeyFrame(Duration.seconds(0), new KeyValue(btn[d - 1].opacityProperty(), .1)),
                    new KeyFrame(Duration.seconds(0.5), new KeyValue(btn[d - 1].opacityProperty(), 1))
            ).play();
            //PAUSE HERE//
        }
    }

Solution

  • You can use the timeline's ability to loop and auto-reverse:

    Timeline t = new Timeline(
                        new KeyFrame(Duration.seconds(0), new KeyValue(btn[d - 1].opacityProperty(), .1)),
                        new KeyFrame(Duration.seconds(0.5), new KeyValue(btn[d - 1].opacityProperty(), 1))
                );
    t.setAutoReverse(true);
    t.setCycleCount(Timeline.INDEFINITE); 
    t.play();