可以自动更新文本动画
package com.example.javafx03;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
import com.example.javafx03.HelloController;
public class HelloApplication extends Application {
@Override
public void start(Stage stage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("hello-view.fxml"));
Parent root = loader.load();
stage.setScene(new Scene(root));
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
-------------------------------------------------------------------------------------------
package com.example.javafx03;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.text.Text;
import javafx.util.Duration;
import java.net.URL;
import java.util.ResourceBundle;
public class HelloController implements Initializable {
int i = 0;
@FXML
private Text text;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
text.setText(String.valueOf(i));
// 创建一个Timeline对象,用于在指定的时间间隔内执行动画
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1),e ->{
i++;
text.setText(String.valueOf(i));
}));
//代码设置了Timeline的循环次数为无限。这意味着动画会一直重复,直到它被停止或场景关闭。
timeline.setCycleCount(Timeline.INDEFINITE);
// 启动动画
timeline.play();
}
}
-----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/23.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.javafx03.HelloController">
<children>
<Text fx:id="text" layoutX="232.0" layoutY="222.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Text">
<font>
<Font size="59.0" />
</font>
</Text>
</children>
</AnchorPane>