一个简单的问题,但我找不到答案。我有一个要实例化多次的 FXML 文件。每个副本都需要有自己的句柄,这样我才能更改其中的数据。假设地,这就像在您刚刚创建的类上使用“new”关键字一样。
到目前为止,在我的尝试中,我已经能够创建 fxml 文件的多个副本,但只有一个 Controller ,因此调用方法意味着所有副本都会发生更改。
我是否必须为同一 fxml 文件的每个副本创建一个新 Controller ?
提前致谢
编辑
我正在研究这个想法的代码在这里:
JavaFX : Pass parameters while instantiating controller class
以防万一一些背景知识可能会有所帮助:
我有一个场景,我想保存我制作的 FXML 文件的多个实例。在场景中设置一个 FXML 文件很容易,但创建多个 (10-20) 意味着我将拥有 10 到 20 个 Controller 和 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
文件的两个实例,并获取对它们的 Controller 的引用:
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它的 Controller
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();
}
关于java - 如何创建一个 fxml 文件的多个实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54586905/