fxml 实现倒计时的功能以及样式
时间: 2023-09-06 10:08:08 浏览: 46
下面是一个使用FXML实现倒计时的例子:
1. 首先,我们需要一个FXML文件来布局我们的UI界面。将以下代码保存为`Countdown.fxml`文件。
```xml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane prefHeight="200.0" prefWidth="320.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="CountdownController">
<Label fx:id="countdownLabel" layoutX="129.0" layoutY="90.0" prefHeight="50.0" prefWidth="62.0" text="10" textAlignment="CENTER" textFill="#0076a3">
<font>
<Font size="36.0" />
</font>
</Label>
<Button fx:id="startButton" layoutX="126.0" layoutY="154.0" mnemonicParsing="false" onAction="#startCountdown" text="Start Countdown" />
</AnchorPane>
```
2. 然后,我们需要一个控制器类来处理FXML文件中定义的UI元素。将以下代码保存为`CountdownController.java`文件。
```java
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.util.Duration;
public class CountdownController {
@FXML
private Label countdownLabel;
@FXML
private Button startButton;
private Timeline timeline;
private int timeSeconds = 10;
@FXML
public void startCountdown() {
if (timeline != null) {
timeline.stop();
}
timeSeconds = 10;
countdownLabel.setText(String.valueOf(timeSeconds));
timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.getKeyFrames().add(
new KeyFrame(Duration.seconds(1),
event -> {
timeSeconds--;
countdownLabel.setText(String.valueOf(timeSeconds));
if (timeSeconds <= 0) {
timeline.stop();
}
}));
timeline.playFromStart();
}
}
```
3. 最后,我们需要一个主类来加载FXML文件并显示UI界面。将以下代码保存为`Main.java`文件。
```java
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("Countdown.fxml"));
primaryStage.setTitle("Countdown");
primaryStage.setScene(new Scene(root, 320, 200));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
4. 运行`Main.java`文件,即可看到一个拥有倒计时功能的UI界面。点击“Start Countdown”按钮即可开始倒计时。
这里只是一个简单的例子,你可以根据自己的需求来调整UI界面的样式。