首页 > 解决方案 > 在 javafx 中,我如何更改按钮的颜色,等待 1 秒而不是更改为默认值?

问题描述

所以我想将按钮的颜色更改为浅绿色,等待 1 秒,然后将其更改回默认值。我怎样才能做到这一点?我试过这样:

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

try { Thread.sleep(1000); }

catch(InterruptedException e) {}

button1.setStyle("");

但我有两个问题:

  1. 颜色从不设置为浅绿色,仅设置为默认值。

  2. 如果我只想将它更改为浅绿色,它只会在等待 1 秒后而不是在它之前更改。

编辑:

所以我开始使用 PauseTransition,但它不会按照我想要的方式工作。

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;
            ...
}

现在的问题是 while() 不会等到按钮恢复默认值,而是开始新的迭代。

标签: javabuttonjavafxfxmlbackground-color

解决方案


  1. 使用-fx-base而不是-fx-background-color.
  2. 使用PauseTransition.
  3. 永远不要Thread.sleep()在 UI 线程上使用。

示例代码:

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

推荐阅读