如果关键帧动画可以在FML中指定,那么许多包含动画的文件格式就可以移植到FML,而不会丢失信息.我知道RotateTransition
等更简单的变体.
将KeyValue目标声明为$text.translateX
(或我能想到的其他变体)的最简单方法会导致类型判断运行时错误.
经过一番摆弄,我设法想出了不会出错的代码,但目标绑定似乎也没有发生.我为此在控制器中添加了一行,以便可以轻松测试想要的行为.如何才能摆脱这一行并使其仅与FML一起工作?它不应该也适用于$text.translateX
吗?
animated.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.animation.*?>
<?import javafx.beans.property.SimpleDoubleProperty?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.Group?>
<?import javafx.scene.Scene?>
<?import javafx.scene.text.Text?>
<?import javafx.util.Duration?>
<?import java.lang.Double?>
<Scene xmlns:fx="http://javafx.com/fxml" fx:controller="org.example.demo.AnimatedController">
<height>240.0</height>
<width>320.0</width>
<fx:define>
<SimpleDoubleProperty fx:id="count"/>
<Timeline fx:id="timeline">
<keyFrames>
<fx:define>
<Double fx:id="endValue0" fx:value="0.0"/>
<Double fx:id="endValue1" fx:value="100.0"/>
</fx:define>
<KeyFrame fx:id="keyFrame0">
<values>
<KeyValue fx:id="keyValue0" endValue="$endValue0">
<target>
<fx:reference source="count"/>
</target>
</KeyValue>
</values>
<time>
<Duration fx:constant="ZERO"/>
</time>
</KeyFrame>
<KeyFrame fx:id="keyFrame1">
<values>
<KeyValue fx:id="keyValue1" endValue="$endValue1">
<target>
<fx:reference source="count"/>
</target>
</KeyValue>
</values>
<time>
<Duration millis="1000"/>
</time>
</KeyFrame>
</keyFrames>
</Timeline>
</fx:define>
<Group>
<Text fx:id="text" y="60" x="${count.value}">Hello, World!</Text>
<Button onAction="#play">Play</Button>
</Group>
</Scene>
AnimatedController.java
package org.example.demo;
import javafx.animation.Timeline;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.text.Text;
public class AnimatedController {
@FXML
private Text text;
@FXML
private Timeline timeline;
@FXML
private SimpleDoubleProperty count = new SimpleDoubleProperty(0);
public void play(ActionEvent ignoredActionEvent) {
text.xProperty().bind(count); // without this line, text.getX() doesn't get updated
count.addListener((_, oldVal, newVal) -> System.out.printf("%s, %s, %s\n", text.getX(), oldVal, newVal));
timeline.play();
}
}
HelloApplication.java
package org.example.demo;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class HelloApplication extends Application {
@Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("animated.fxml"));
Scene scene = fxmlLoader.load();
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}