JavaFx在不同的fxml文件加载时传递参数问题

一、问题

典型的JavaFX程序Main,fxml,Controller 之间的加载关系是这样的,Main启动程序,加载fxml,再由 fxml 加载指定的 controller,这个过程是单向的,所以其实 fxml 中并没法绑定 Main 中的 stage和scene,必须由 Main 加载一个 stage 后,由 fxml 文件对进行初始化设置,所以 fxml 文件不会指定 Stage,Scene,一般由 Main 来指定 Stage 及其对应的 Scene,或者将Main中的Stage对象传递给Controller 来进行设置。相应的Scene绑定FXMLLoader读取到的其他页面的fxml文件获取的Root对象,这样就可以实现在Controller中控制页面切换逻辑。

但现在我有这样一个需求,我要将当前窗口的参数传递给一个辅助窗口,那该怎么办?

stackoverflow上找到了解决方案,这里简单总结一下。

二、解决方案

@FXML
private HBox main;//界面切换的容器
 
public void show(Customer customer) {
  FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));
  //load必须要先执行,否则下面的controller是null
  Parent root =loader.load();
  TestController controller = loader.getController();
  controller.initData("123");
 
  main.getChildren().clear();
  main.getChildren().add(root);
}

这里将之前加载fxml文件的过程分解了,加载后,通过initData给controller传递参数

控件代码:

public class TestController implements Initializable{
  @FXML private Label name;
  void initialize() {}
  void initData(String name) {
    name.setText(name);
  }
}

值得注意的是fxml文件中关联controller的部分不要做修改。

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>


<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="TestController">
   <children>
      <Label fx:id="name" layoutX="199.0" layoutY="149.0" text="Label" />
   </children>
</AnchorPane>

 

posted @ 2021-03-14 11:13  王陸  阅读(985)  评论(0编辑  收藏  举报