如何创建一个 fxml 文件的多个实例化

How to create multiple instantiations of one fxml file

一个简单的问题,但我找不到答案。我有一个要实例化多次的 FXML 文件。每个副本都需要有自己的句柄,这样我才能更改其中的数据。假设地,这与在您刚刚创建的 class 上使用 "new" 关键字完全一样。

到目前为止,我已经能够创建 fxml 文件的多个副本,但只有一个控制器,因此调用方法意味着所有副本都会发生更改。

是否必须为同一 fxml 文件的每个副本创建一个新控制器?

提前致谢

编辑

我正在研究这个想法的代码在这里:

以防万一一些背景知识可能有所帮助:

我有一个场景,我想保存我制作的 FXML 文件的多个实例。在场景中设置一个 FXML 文件很容易,但创建多个 (10-20) 意味着我将拥有 10 到 20 个控制器和 10 到 20 个 FXML 文件实例。有更简洁的方法吗?

我希望做这样的事情:

public class SampleController implements Initializable {

    @FXML
    Label firstName;

    @FXML
    Label lastName;

    public SampleController(Label firstname, Label lastname) {

        this.firstName = firstname;
        this.lastName = lastname;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }
}

然后像这样调用:

SampleController Row1 = new SampleController("my", "name");

并让此命令将附加的 FXML 文件连同我传递给它的数据一起加载到场景中。但这不起作用,它异常崩溃。

下面演示了构建一个 fxml 文件的两个实例,并获取对其控制器的引用:

Main.fxml

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

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
   <children>
      <Label fx:id="label" />
   </children>
   <opaqueInsets>
      <Insets top="10.0" />
   </opaqueInsets>
 </Pane>

Controller.java其控制者

import javafx.fxml.FXML;
import javafx.scene.control.Label;

public class Controller{

    @FXML
    public Label label;

    public void setText(String text) {
        label.setText(text);
    }
}

使用两个实例 Main.fxml :

@Override
public void start(final Stage primaryStage) throws Exception{

    FXMLLoader loader = new FXMLLoader();
    Pane topPane  =  loader.load(getClass().getResource("xml/Main.fxml").openStream());
    Controller controllerOfTop = loader.getController();
    controllerOfTop.setText("Top");

    loader = new FXMLLoader();
    Pane bottomPane  =  loader.load(getClass().getResource("xml/Main.fxml").openStream());
    Controller controllerOfBottom = loader.getController();
    controllerOfBottom.setText("Bottom");

    Scene scene = new Scene(new VBox(topPane, bottomPane));
    primaryStage.setScene(scene);
    primaryStage.show();
}