button - 单击时临时更改按钮的颜色
问题描述
我需要临时更改单击按钮的背景颜色 0.5 秒,然后希望它恢复为原始颜色。
我尝试过使用 pausetransition,但我对 java 很陌生,不知道如何正确使用它。现在我能做的最好的就是让他的按钮在点击时保持新的颜色。
Color[] colors = new Color[]{Color.DARKORCHID,Color.SALMON,Color.SPRINGGREEN,Color.GOLD};
Color randomColor = colors[(new Random().nextInt(4))];
button.setBackground(new Background(new BackgroundFill(randomColor,null,null)));
grid.add(button, column, row);
button.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent e){
Button b = (Button)e.getSource();
Button save = b;
b.setBackground(new Background(new BackgroundFill(Color.LIGHTGRAY,null,null)));
}
});
}
现在只是将颜色更改为灰色。如果我能弄清楚如何让颜色暂时改变甚至在再次点击时变回来。我的问题的另一部分是所有按钮都有不同的颜色。任何提示或帮助将不胜感激。
解决方案
对于Button
您创建的每个,您需要创建PauseTransition
一个持续时间为半秒的 ,这会将背景设置回原来的状态。当您单击 时,Button
您会将背景更改为灰色背景并重新启动PauseTransition
. 这将使背景在最后一次单击后恢复半秒。这是一个小例子:
import java.util.Random;
import javafx.animation.Animation.Status;
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
GridPane root = new GridPane();
root.setAlignment(Pos.CENTER);
root.setHgap(10);
root.setVgap(10);
root.setPadding(new Insets(10));
fillGrid(root);
primaryStage.setScene(new Scene(root, 500, 300));
primaryStage.show();
}
private static void fillGrid(GridPane grid) {
Background[] backgrounds = {
new Background(new BackgroundFill(Color.DARKORCHID, null, null)),
new Background(new BackgroundFill(Color.SALMON, null, null)),
new Background(new BackgroundFill(Color.SPRINGGREEN, null, null)),
new Background(new BackgroundFill(Color.GOLD, null, null))
};
Background greyBg = new Background(new BackgroundFill(Color.GREY, null, null));
Random rand = new Random();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
Background original = backgrounds[rand.nextInt(backgrounds.length)];
Button button = new Button(String.format("(%d,%d)", i, j));
button.setBackground(original);
PauseTransition transition = new PauseTransition(Duration.seconds(0.5));
transition.setOnFinished(event -> button.setBackground(original));
button.setOnMouseClicked(event -> {
event.consume();
button.setBackground(greyBg);
transition.playFromStart();
});
grid.add(button, j, i);
}
}
}
}
推荐阅读
- android - 在 Android 意图中传递模拟类
- php - 将 b64 图片支持添加到 HTML Purifier 的默认白名单中
- java - 是否可以强制 Eclipse 为已编译的 java 类保留准确的行号?
- vba - 比较vba中的日期
- angular - 如何在 nx 库中使用 APP_INITIALIZER?
- raspberry-pi - LoRa 点对点限制
- azure - 使用 Batch-Shipyard 在虚拟网络中配置 Azure Batch 池
- vba - 如果工作簿已打开,则继续
- laravel - 如何在锚标记数据值中设置图像 url
- ios - iOS中的压缩PNG文件错误组