java - 在 javafx 中,我如何更改按钮的颜色,等待 1 秒而不是更改为默认值?
问题描述
所以我想将按钮的颜色更改为浅绿色,等待 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
. - 永远不要
Thread.sleep()
在 UI 线程上使用。
示例代码:
button.setStyle("-fx-base: lightgreen");
PauseTransition pause = new PauseTransition(
Duration.seconds(1),
);
pause.setOnFinished(event -> {
button.setStyle(null);
});
pause.play();
推荐阅读
- c# - 如何在 C# EF 核心 web api 中将列表转换为 Json
- python - python递归追加到列表
- c# - BindingSource.EndEdit() 与 TableAdapterManager.UpdateAll()
- c - 为什么我无法释放内存?无效的 free() / delete / delete[] / realloc()
- testing - 如何pytest从数据库读取的函数?
- angular - 使用 Observable 获取数据时,需要使用detector.detectChanges Angular v6+
- r - 竞争风险/生存分析 R
- .net - 在 .net 3.1 凭据错误中调用 Powershell 核心中的 Restart-Computer 但在 Powershell 中工作
- python - 如何使用 Python 中的 playsound 模块同时播放两种声音?
- javascript - JavaScript - 如何切换 setInterval