在javafx中,我如何更改按钮的颜色,请等待1秒钟,然后再更改为默认值?

问题描述 投票:1回答: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()不会等到按钮变回默认值,它才会开始新的迭代。

java button javafx fxml background-color
1个回答
0
投票
  1. 使用-fx-base代替-fx-background-color
  2. 使用PauseTransition
  3. 请勿在UI线程上使用Thread.sleep()

示例代码:

button.setStyle("-fx-base: lightgreen");
PauseTransition pause = new PauseTransition(
    Duration.seconds(1),
);
pause.setOnFinished(event -> {
    button.setStyle(null);
});
pause.play();    
© www.soinside.com 2019 - 2024. All rights reserved.