0

I have a Text and an input field. If the input is correct for the text, the background of the input field should change to green. Then the program should stop for 1 second (and display the input) Then it should generate a new Text with random() and change the color back to white.

input.setOnKeyPressed(e -> {
        if (e.getCode() == KeyCode.ENTER) {
            if(value.equals(input.getText())){
                input.setStyle("-fx-background-color: green");
                System.out.println("right!");

                // now it should wait 1 second
                // and display only the input & green background
                try{ Thread.sleep(1000);
                } catch(InterruptedException i){
                   throw new Error("interrupted");
                }

                // random changes the Text and the input will reset
                random(); 
                input.setText("");
                input.setStyle("-fx-background-color: white");
            }
            else{
                System.out.println("false");
            }
        }
      });

But the problem is, that the background never changes to green. For this one second it is only displaying my input. Then I get a new Text and my background changes to white.

Have you any ideas how to change the background color for this time? Thanks for your answers!

EDIT

It works with PauseTransition instead of Thread so:

PauseTransition wait = new PauseTransition(Duration.seconds(1));
                wait.setOnFinished(event -> {
                    random();
                    input.setStyle("-fx-background-color: white");
                    input.setText("");
                });
                wait.play();
noteZ
  • 11
  • 2
  • 1
    The program does "stop for 1 second", which is why you don't see the green text (the program cannot update the UI, since it is "stopped"). You should *never* block the UI thread. Use a `PauseTransition` for functionality like this. – James_D Mar 19 '18 at 18:39
  • See if you can figure it out using [this](https://stackoverflow.com/questions/9966136/javafx-periodic-background-task) code. If you can't, come back with an altered question. – SedJ601 Mar 19 '18 at 18:39
  • Or [this](https://stackoverflow.com/a/35370618/2189127), which is perhaps a little simpler. – James_D Mar 19 '18 at 18:41
  • Thanks a lot guys! Edited my question – noteZ Mar 19 '18 at 19:00

0 Answers0