【问题标题】:how to load 2 fxml files in the same time如何同时加载 2 个 fxml 文件
【发布时间】:2015-11-08 15:21:23
【问题描述】:

我有两个 javafx 窗格,“pane1”和“pane2”(“pane1”是“pane2”的第一个父级)。如何加载两个 fxml 文件,同时说“fxml1.fxml”和“fxml2.fxml”,同时在“pane1”中加载“fxml1.fxml”,在“pane2”中加载“fxml2.fxml”。

这是我尝试过的。但这只会加载 fxml1.fxml 文件,而不会加载 fxml2.fxml 文件...

public class HostelController implements Initializable {
    @FXML
    private Button hostlersBut;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

    }

    @FXML
    private void hostlersClkHostel(ActionEvent event) {
        try {
            pane1.getChildren().clear();
            pane1.getChildren().add(FXMLLoader.load(getClass().getResource("fxml1.fxml")));

            pane2.getChildren().clear();
            pane2.getChildren().add(FXMLLoader.load(getClass().getResource("fxml2.fxml")));
        } catch (IOException ex) {
            System.out.print(ex);
        }
    }
}

这是当前视图的 fxml 文件

<AnchorPane id="AnchorPane" fx:id="anchorPane" prefHeight="508.0" prefWidth="968.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.HostelController">
    <children>
      <Pane fx:id="pane1" prefHeight="538.0" prefWidth="1014.0" AnchorPane.leftAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
            <Button fx:id="hostelersBut" layoutX="7.0" layoutY="100.0" onAction="#hostelAction" prefHeight="30.0" prefWidth="150.0" text="Hostel"> </Button>
            <Pane fx:id="pane2" layoutX="166.0" prefHeight="538.0" prefWidth="846.0">
               <children>
               </children>
            </Pane>
         </children>
      </Pane>
    </children>
</AnchorPane>

这是一个最小的代码,还有一些其他的按钮,所以我不能使用初始化方法来初始化一个窗格加载...正如我所说,只有第一个 fxml 文件被加载,第二个没有...

【问题讨论】:

  • 加载一个 FXML 文件的方式与加载一个 FXML 文件的方式相同,只是您执行了两次...发布一些代码来展示您的尝试。
  • @James_D 我刚刚添加了代码...
  • 应该没问题。发布minimal reproducible example
  • 这是最小尺寸的控制器...它不会加载第二个 fxml 文件或至少清除窗格2...
  • “fxml1.fxml”文件重新加载整个视图,我认为一旦“fxml1.fxml”文件被加载,按钮点击动作就会被忽略,因为视图有一组新的项目。 ..

标签: java javafx fxml


【解决方案1】:

在您的 FXML 中,pane2pane1 的子代。因此,当您调用 pane1.getChildren().clear() 时,您会从 UI 中完全删除 pane2。您需要 pane1pane2 才能在它们之间建立父/子关系。

取决于你真正想要发生的事情,比如

<AnchorPane id="AnchorPane" fx:id="anchorPane" prefHeight="508.0" prefWidth="968.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.HostelController">
    <children>
      <Pane fx:id="pane1" prefHeight="538.0" prefWidth="1014.0" AnchorPane.leftAnchor="0.0" AnchorPane.topAnchor="0.0" />

      <Button fx:id="hostelersBut" layoutX="7.0" layoutY="100.0" onAction="#hostelAction" prefHeight="30.0" prefWidth="150.0" text="Hostel"> </Button>
      <Pane fx:id="pane2" layoutX="166.0" prefHeight="538.0" prefWidth="846.0" />
    </children>
</AnchorPane>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多