我在FXML文件中有一个容器(让我们将其称为主容器带有主控制器),并试图生成其他FXML创建的节点并将它们添加为子节点主要容器。JavaFX:在运行时加载FXML并与控制器通信
我不认为我可以通过嵌套FXML来做到这一点,因为节点被添加到需要调用函数的自定义组件中。我想我可以加载主控制器的初始化中的节点,但这会导致堆栈溢出,因为加载会递归调用初始化函数。
这样做的最好方法是什么?我希望能够让主控制器响应并设置节点。我可以
主控制器的样子:
public class MainController implements Initializable {
@FXML
private CardPane cardPane;
@Override
public void initialize(URL url, ResourceBundle rb) {
// setup panes
AnchorPane importPane = new AnchorPane();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("ImportPane.fxml"));
fxmlLoader.setRoot(importPane);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
cardPane.addCard(importPane);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
CardPane是自定义组件类,其中addCard添加一个节点(CardLayout的实现)。
ImportPane的FXML现在几乎是空的。我只有一个CSS类型的根类,所以我可以看到它的布局。
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<fx:root id="AnchorPane" prefHeight="400.0" prefWidth="600.0" styleClass="mainFxmlClass" type="AnchorPane" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.40">
<stylesheets>
<URL value="@view.css" />
</stylesheets>
<children>
<VBox alignment="CENTER" layoutX="121.0" layoutY="38.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" styleClass="importPane" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</fx:root>
为主要成分的FXML是:
<?xml version="1.0" encoding="UTF-8"?>
<?import cardPane.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" stylesheets="@PHASIQAnalyzerView.css" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="phasiqplateanalyzer.PHASIQAnalyzerController">
<children>
<VBox alignment="CENTER" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<HBox id="buttonBar" alignment="CENTER" maxHeight="-Infinity" maxWidth="1.7976931348623157E308" minWidth="-Infinity" prefHeight="100.0" prefWidth="200.0" />
<CardPane id="mainPane" fx:id="cardPane" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS" />
</children>
</VBox>
</children>
</AnchorPane>
句法有点不同,但t他的想法是对的。 –
新的初始化工作是: –
// //设置窗格 FXMLLoader mainfxmlLoader = new FXMLLoader(getClass()。getResource(“PHASIQAnalyzerView.fxml”)); mainfxmlLoader.setController(this); AnchorPane importPane = new AnchorPane(); FXMLLoader fxmlLoader = new FXMLLoader(getClass()。getResource(“ImportPane.fxml”)); fxmlLoader.setRoot(importPane); fxmlLoader.setController(this); 尝试{...' –