JavaFX - How to get FXML Controller? [duplicate]

…衆ロ難τιáo~ 提交于 2019-11-29 18:22:13

问题


This question already has an answer here:

  • Accessing FXML controller class 4 answers

I have the following code:

Parent parent = FXMLLoader.load(Main.class.getResource("JanelaPrincipal.fxml"));

in the fxml file there is a reference to the controller class. How can I get the controller object?


fxml:

<AnchorPane id="AnchorPane" fx:id="root" 
    prefHeight="768.0" prefWidth="1024.0" xmlns:fx="http://javafx.com/fxml/1" 
    xmlns="http://javafx.com/javafx/2.2" 
    fx:controller="br.meuspila.javafx.JanelaPrincipalController">
    ...

回答1:


Instantiate an FXMLLoader and use an instance load method rather than a class static load method. You can then retrieve the controller instance from the loader instance.

FXMLLoader loader = new FXMLLoader(
  getClass().getResource(
    "customerDialog.fxml"
  )
);

Pane pane = (Pane) loader.load();

CustomerDialogController controller = 
    loader.<CustomerDialogController>getController();
controller.initData(customer);

For more info see:

  • Passing Parameters JavaFX FXML


来源:https://stackoverflow.com/questions/25828561/javafx-how-to-get-fxml-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!