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

≡放荡痞女 提交于 2020-12-15 05:04:21

问题


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:


  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();    


来源:https://stackoverflow.com/questions/59730739/in-javafx-how-do-i-change-the-color-of-a-button-wait-1-second-than-change-it-ba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!