【发布时间】:2020-04-30 23:59:37
【问题描述】:
所以我想将按钮的颜色更改为浅绿色,等待 1 秒,然后将其更改回默认值。 我怎样才能做到这一点?我是这样尝试的:
button1.setStyle("-fx-background-color: lightgreen");
try { Thread.sleep(1000); }
catch(InterruptedException e) {}
button1.setStyle("");
但我有两个问题:
颜色从不设置为浅绿色,仅设置为默认值。
如果我只想将其更改为浅绿色,它只会在等待 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() 不会等到按钮恢复默认值,而是开始新的迭代。
【问题讨论】:
-
尝试
-fx-base而不是-fx-background-color。查看PauseTransition。切勿在 UI 线程上使用Thread.sleep()。 -
我现在正在尝试 PauseTransition,但问题是,程序不会等待 1 秒,只有按钮会变成浅绿色 1 秒。因为我希望这一切都在一个循环中,所以我也需要程序等待。
-
“我需要程序等待”是什么意思?您可能需要添加更多代码 (minimal reproducible example) 来解释这一点。或者问一个新问题,因为颜色变化和暂停似乎可以使用 PauseTransiton 来回答。
-
我有一段时间(i
-
我使用过伪类更改,动态更改伪类比样式更有效,请参阅stackoverflow.com/questions/37072514/…
标签: java button javafx fxml background-color