Search code examples
javafxsleeptimeunit

javafx label message showing with timer does not work


So im trying to show a message in javafx on a label and then make it disapear after 1 second. Im able to show the message as desired but i cannot make it dissapear. Actually my problem is that i never appear. So if i use only this:

lbReserva.setText("RESERVA REALITZADA");

Works as expected but obviously it just stay like that. So then i tried this:

        try {
        lbReserva.setText("RESERVA REALITZADA");
        TimeUnit.SECONDS.sleep(1); 
        lbReserva.setText("");           
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }

But then the label it just never appears. I've tried placing the first set text outside right before the try block. I've tried placing the second set text just after the catch. In any case i got the same result, the label never appears, or probably appears and straight away dissapear. Any clues what im doing wrong? thank you so much in advance.

pd: i have tried using Thread.sleep instead of TimeUnit but i got the same result.


Solution

  • Use PauseTransition.

    import javafx.animation.PauseTransition;
    import javafx.application.Application;
    import static javafx.application.Application.launch;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    public class TestingGround extends Application
    {
        @Override
        public void start(Stage stage) throws Exception
        {
            Label label = new Label("Hello World!");
            PauseTransition wait = new PauseTransition(Duration.seconds(1));
            wait.setOnFinished((e) -> {
                label.setVisible(false);
            });
            wait.play();
            VBox root = new VBox(label);
            stage.setScene(new Scene(root, 700, 500));
            stage.show();
        }
    
        public static void main(String[] args)
        {
            launch(args);
        }    
    }
    

    enter image description here