Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX - How to get FXML Controller? [duplicate]

Tags:

java

javafx

fxml

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">
    ...
like image 540
ceklock Avatar asked Sep 13 '14 23:09

ceklock


People also ask

Can two FXML have same controller?

It's possible to use the same controller class for multiple FXML files, but your code will be really hard to follow, and it's a very bad idea. (Also note that using the fx:controller attribute, you will have a different controller instance each time you call FXMLLoader.

How do controllers work in JavaFX using FXML?

JavaFX controller works based on MVC(Model-View-Controller) JavaFX MVC can be achieved by FXML (EFF-ects eXtended Markup Language). FXML is an XML based language used to develop the graphical user interfaces for JavaFX applications as in the HTML.

Is XML the same as FXML?

FXML is an XML-based language that provides the structure for building a user interface separate from the application logic of your code.

Is FXML annotation required?

The @FXML annotation is required for the controller class's private member fields; otherwise, field injection would fail.


1 Answers

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
like image 116
jewelsea Avatar answered Oct 05 '22 04:10

jewelsea