我想在启动时就设置更新Label内容,该怎么写?
Main类
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 {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"));
Parent root = loader.load();
Controller controller = loader.getController(); // 获取控制器实例
// 显示场景和舞台
Scene scene = new Scene(root, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
}
控制器
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class Controller {
@FXML
public Label globalLabel; // 全局的JavaFXLabel变量
// 其他方法...
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.FireworkRocket.Controller">
<children>
<Label fx:id="globalLabel" text="初始内容" />
</children>
</AnchorPane>