简体   繁体   中英

In javafx how do i change the color of a button, wait 1 second than change it back do default?

So i want to change the color of a button to light green, wait 1 second than change it back to default. How can i do this? I tried it this way:

button1.setStyle("-fx-background-color: lightgreen");

try { Thread.sleep(1000); }

catch(InterruptedException e) {}

button1.setStyle("");

But i have 2 problems:

  1. the color never sets to light green, only to default.

  2. if i want to change it only to light green, it only changes after the 1 second of waiting and not before it.

Edit:

So i got to the part to use PauseTransition, but it won't work the way i want it to.

for(int i=0; i<n; i++) {
   int x = rand.nextInt(4) + 1;
            switch(x) {
                case 1: {
                    System.out.println("b1");
                    button1.setStyle("-fx-background-color: lightgreen; -fx-border-color: black;");

                    PauseTransition wait = newPauseTransition(Duration.seconds(1));
                    wait.setOnFinished(event -> {
                    button1.setStyle("");
                });
                wait.play();
            }
            break;
            case 2: {
                System.out.println("b2");
                button2.setStyle("-fx-background-color: lightgreen; -fx-border-color: black;");

                PauseTransition wait = new PauseTransition(Duration.seconds(1));
                wait.setOnFinished(event -> {
                    button2.setStyle("");
                });
                wait.play();
            }
            break;
            ...
}

Now the problem is that the while() won't wait until the button turns back to default, and it starts a new iteration.

  1. Use -fx-base instead of -fx-background-color .
  2. Use PauseTransition .
  3. Never use Thread.sleep() on the UI thread.

Sample code:

button.setStyle("-fx-base: lightgreen");
PauseTransition pause = new PauseTransition(
    Duration.seconds(1),
);
pause.setOnFinished(event -> {
    button.setStyle(null);
});
pause.play();    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM