JavaFX过渡:反转按钮颜色

时间:2016-10-02 12:39:58

标签: javafx javafx-2 javafx-8 transition

我想将按钮的颜色更改为反转颜色,然后返回过渡。

我能够使用ColorAdjust的Timeline来实现亮度,但我没有找到一个效果类来转换按钮的颜色和时间轴。

希望有人可以帮助我吗? 谢谢!

1 个答案:

答案 0 :(得分:3)

使用Blend效果BlendMode.DIFFERENCEtopInput可以实现反转效果,黑色表示无反转,白色表示完全反转的颜色。例如:

@Override
public void start(Stage primaryStage) {
    Blend blendEffect = new Blend(BlendMode.DIFFERENCE);
    ColorInput input = new ColorInput();
    blendEffect.setTopInput(input);
    Button btn = new Button("Inversion Animation");
    input.widthProperty().bind(btn.widthProperty());
    input.heightProperty().bind(btn.heightProperty());
    btn.setEffect(blendEffect);
    btn.setStyle("-fx-body-color: orange;");

    DoubleProperty brightness = new SimpleDoubleProperty(0);
    input.paintProperty().bind(Bindings.createObjectBinding(() -> Color.BLACK.interpolate(Color.WHITE, brightness.get()), brightness));

    Timeline timeline = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(brightness, 0d)),
            new KeyFrame(Duration.seconds(1), new KeyValue(brightness, 1d))
    );
    timeline.setOnFinished(evt -> timeline.setRate(-timeline.getRate()));

    btn.setOnAction((ActionEvent event) -> {
        timeline.play();
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 500, 500);

    primaryStage.setScene(scene);
    primaryStage.show();
}