1

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.

  • 3
    This SO question is not exactly what you need but it may help you find a solution. [Flashing label in javafx gui](https://stackoverflow.com/questions/43084698/flashing-label-in-javafx-gui). Note that you should ___never___ call method `sleep()` from the JavaFX application thread. – Abra Feb 17 '20 at 19:54
  • 1
    Maybe this SO question is closer to what you need: [How to make a Text content disappear after some time in JavaFX?](https://stackoverflow.com/questions/23190049/how-to-make-a-text-content-disappear-after-some-time-in-javafx) – Abra Feb 17 '20 at 19:56

1 Answers1

2

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

SedJ601
  • 12,173
  • 3
  • 41
  • 59