如何在JavaFX中使用CSS制作动画?

15

我希望通过更改节点的样式类来改变Node的样式。

Button button = new Button();
button.getStyleClass().add("class1")   
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            button.getStyleClass().add("class2");
        }
    });

是否可以逐渐改变样式,制作类似于过渡效果的东西?


除了你的问题之外:为什么不在你的示例代码中使用花式 Lambda 注释?而不是(new Eventhan...),你只需编写:mouseEvent -> button.getStyleClass().add("class2")。花式吗? - Sauer
4个回答

21

是否可以逐渐改变样式?例如进行一些过渡效果?

可以。

您需要使用setStyle而不是样式类,因为样式类是在CSS中定义的静态内容。在JavaFX CSS中没有直接支持动画效果。您需要在Java代码中执行动画步骤以修改CSS样式。

我只建议在要使用CSS执行过渡效果时才使用此方法,因为没有相应的Java可用API。

为了处理动画效果,您可以使用标准的JavaFX动画Timeline来操作依赖于CSS样式属性的属性。

例如,将您的样式属性绑定到字符串。然后在时间轴中变化您要更改的组件(在本例中为colorStringProperty)。

warningButton.styleProperty().bind(
    new SimpleStringProperty("-fx-base: ")
        .concat(colorStringProperty)
        .concat(";")
        .concat("-fx-font-size: 20px;")
);

以下是一个示例,使用 CSS 来让按钮闪烁。当按下按钮时,它的基础颜色从灰色逐渐变为红色。

warninggray warningred

import javafx.animation.*;
import javafx.application.Application;
import javafx.beans.property.*;
import javafx.beans.value.*;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.*;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;

/** Shows how you can modify css styles dynamically using a timeline. */
public class Warning extends Application {

    private static final String BACKGROUND = "http://bobgreiner.tripod.com/1cc2ce10.jpg"; 

    @Override
    public void start(Stage stage) throws Exception{
        final ObjectProperty<Color> warningColor = new SimpleObjectProperty<>(Color.GRAY);
        final StringProperty colorStringProperty = createWarningColorStringProperty(warningColor);

        StackPane layout = new StackPane();
        layout.getChildren().addAll(
                new ImageView(new Image(BACKGROUND)),
                createWarningButton(
                        warningColor, 
                        colorStringProperty
                )
        );
        stage.setScene(new Scene(layout));
        stage.show();
    }

    private StringProperty createWarningColorStringProperty(final ObjectProperty<Color> warningColor) {
        final StringProperty colorStringProperty = new SimpleStringProperty();
        setColorStringFromColor(colorStringProperty, warningColor);
        warningColor.addListener(new ChangeListener<Color>() {
            @Override
            public void changed(ObservableValue<? extends Color> observableValue, Color oldColor, Color newColor) {
                setColorStringFromColor(colorStringProperty, warningColor);
            }
        });

        return colorStringProperty;
    }

    private Button createWarningButton(final ObjectProperty<Color> warningColor, StringProperty colorStringProperty) {
        final Button warningButton = new Button("Warning! Warning!");
        warningButton.styleProperty().bind(
                new SimpleStringProperty("-fx-base: ")
                        .concat(colorStringProperty)
                        .concat(";")
                        .concat("-fx-font-size: 20px;")
        );

        warningButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                Timeline flash = new Timeline(
                    new KeyFrame(Duration.seconds(0),    new KeyValue(warningColor, Color.GRAY, Interpolator.LINEAR)),
                    new KeyFrame(Duration.seconds(0.25), new KeyValue(warningColor, Color.GRAY, Interpolator.LINEAR)),
                    new KeyFrame(Duration.seconds(1),    new KeyValue(warningColor, Color.RED,  Interpolator.LINEAR)),
                    new KeyFrame(Duration.seconds(1.25), new KeyValue(warningColor, Color.RED,  Interpolator.LINEAR))
                );
                flash.setCycleCount(6);
                flash.setAutoReverse(true);
                flash.play();
            }
        });

        return warningButton;
    }

    private void setColorStringFromColor(StringProperty colorStringProperty, ObjectProperty<Color> color) {
        colorStringProperty.set(
                "rgba("
                        + ((int) (color.get().getRed()   * 255)) + ","
                        + ((int) (color.get().getGreen() * 255)) + ","
                        + ((int) (color.get().getBlue()  * 255)) + ","
                        + color.get().getOpacity() +
                ")"
        );
    }

    public static void main(String[] args) {
        launch(args);
    }
}

5

7
他询问的是CSS动画,而不是编程动画。 - specializt
1
我知道。Jewelsea提到,JavaFX不支持CSS动画,需要执行单个动画步骤。我只是想澄清,如果您使用转换,这是不必要的。 - Franz Deschler

0

我开了一个问题来添加这个功能。所以,当这个问题得到解决时,JavaFX就可以支持纯CSS动画。


0

CSS转换似乎还在不断发展中,您可以在openjdk/jfx#870上关注它。

拉取请求中显示的示例:

.button {
    -fx-background-color: dodgerblue;
}

.button:hover {
    -fx-background-color: red;
    -fx-scale-x: 1.1;
    -fx-scale-y: 1.1;

    transition: -fx-background-color 0.5s ease,
                -fx-scale-x 0.5s ease,
                -fx-scale-y 0.5s ease;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接