Passing Parameters JavaFX FXML











up vote
157
down vote

favorite
115












How can I pass parameters to a secondary window in javafx? Is there a way to communicate with the corresponding controller?



For example:
The user chooses a customer from a TableView and a new window is opened, showing the customer's info.



Stage newStage = new Stage();
try
{
AnchorPane page = (AnchorPane) FXMLLoader.load(HectorGestion.class.getResource(fxmlResource));
Scene scene = new Scene(page);
newStage.setScene(scene);
newStage.setTitle(windowTitle);
newStage.setResizable(isResizable);
if(showRightAway)
{
newStage.show();
}
}


newStage would be the new window. The problem is, I can't find a way to tell the controller where to look for the customer's info (by passing the id as parameter).



Any ideas?










share|improve this question
























  • Check to see if this works too: stackoverflow.com/questions/14370183/…
    – Dynelight
    Jan 21 '13 at 4:32










  • @Alvaro: did you get your solution? can you pass parameter? from one controller to another controller file?
    – Java Man
    Mar 7 '14 at 4:47






  • 2




    Yes. jewelsea gave a book-level explanation. That's why I accepted his answer
    – Alvaro
    Mar 7 '14 at 12:40















up vote
157
down vote

favorite
115












How can I pass parameters to a secondary window in javafx? Is there a way to communicate with the corresponding controller?



For example:
The user chooses a customer from a TableView and a new window is opened, showing the customer's info.



Stage newStage = new Stage();
try
{
AnchorPane page = (AnchorPane) FXMLLoader.load(HectorGestion.class.getResource(fxmlResource));
Scene scene = new Scene(page);
newStage.setScene(scene);
newStage.setTitle(windowTitle);
newStage.setResizable(isResizable);
if(showRightAway)
{
newStage.show();
}
}


newStage would be the new window. The problem is, I can't find a way to tell the controller where to look for the customer's info (by passing the id as parameter).



Any ideas?










share|improve this question
























  • Check to see if this works too: stackoverflow.com/questions/14370183/…
    – Dynelight
    Jan 21 '13 at 4:32










  • @Alvaro: did you get your solution? can you pass parameter? from one controller to another controller file?
    – Java Man
    Mar 7 '14 at 4:47






  • 2




    Yes. jewelsea gave a book-level explanation. That's why I accepted his answer
    – Alvaro
    Mar 7 '14 at 12:40













up vote
157
down vote

favorite
115









up vote
157
down vote

favorite
115






115





How can I pass parameters to a secondary window in javafx? Is there a way to communicate with the corresponding controller?



For example:
The user chooses a customer from a TableView and a new window is opened, showing the customer's info.



Stage newStage = new Stage();
try
{
AnchorPane page = (AnchorPane) FXMLLoader.load(HectorGestion.class.getResource(fxmlResource));
Scene scene = new Scene(page);
newStage.setScene(scene);
newStage.setTitle(windowTitle);
newStage.setResizable(isResizable);
if(showRightAway)
{
newStage.show();
}
}


newStage would be the new window. The problem is, I can't find a way to tell the controller where to look for the customer's info (by passing the id as parameter).



Any ideas?










share|improve this question















How can I pass parameters to a secondary window in javafx? Is there a way to communicate with the corresponding controller?



For example:
The user chooses a customer from a TableView and a new window is opened, showing the customer's info.



Stage newStage = new Stage();
try
{
AnchorPane page = (AnchorPane) FXMLLoader.load(HectorGestion.class.getResource(fxmlResource));
Scene scene = new Scene(page);
newStage.setScene(scene);
newStage.setTitle(windowTitle);
newStage.setResizable(isResizable);
if(showRightAway)
{
newStage.show();
}
}


newStage would be the new window. The problem is, I can't find a way to tell the controller where to look for the customer's info (by passing the id as parameter).



Any ideas?







javafx parameters dependency-injection parameter-passing fxml






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 '16 at 19:27









RAnders00

2,94132350




2,94132350










asked Jan 6 '13 at 23:33









Alvaro

5,66652848




5,66652848












  • Check to see if this works too: stackoverflow.com/questions/14370183/…
    – Dynelight
    Jan 21 '13 at 4:32










  • @Alvaro: did you get your solution? can you pass parameter? from one controller to another controller file?
    – Java Man
    Mar 7 '14 at 4:47






  • 2




    Yes. jewelsea gave a book-level explanation. That's why I accepted his answer
    – Alvaro
    Mar 7 '14 at 12:40


















  • Check to see if this works too: stackoverflow.com/questions/14370183/…
    – Dynelight
    Jan 21 '13 at 4:32










  • @Alvaro: did you get your solution? can you pass parameter? from one controller to another controller file?
    – Java Man
    Mar 7 '14 at 4:47






  • 2




    Yes. jewelsea gave a book-level explanation. That's why I accepted his answer
    – Alvaro
    Mar 7 '14 at 12:40
















Check to see if this works too: stackoverflow.com/questions/14370183/…
– Dynelight
Jan 21 '13 at 4:32




Check to see if this works too: stackoverflow.com/questions/14370183/…
– Dynelight
Jan 21 '13 at 4:32












@Alvaro: did you get your solution? can you pass parameter? from one controller to another controller file?
– Java Man
Mar 7 '14 at 4:47




@Alvaro: did you get your solution? can you pass parameter? from one controller to another controller file?
– Java Man
Mar 7 '14 at 4:47




2




2




Yes. jewelsea gave a book-level explanation. That's why I accepted his answer
– Alvaro
Mar 7 '14 at 12:40




Yes. jewelsea gave a book-level explanation. That's why I accepted his answer
– Alvaro
Mar 7 '14 at 12:40












8 Answers
8






active

oldest

votes

















up vote
226
down vote



accepted










Recommended Approach



This answer enumerates different mechanisms for passing parameters to FXML controllers.



For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.



For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.



Passing Parameters Directly From the Caller to the Controller



Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.



Something like the following code:



public Stage showCustomerDialog(Customer customer) {
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"customerDialog.fxml"
)
);

Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(
new Scene(
(Pane) loader.load()
)
);

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

stage.show();

return stage;
}

...

class CustomerDialogController {
@FXML private Label customerName;
void initialize() {}
void initData(Customer customer) {
customerName.setText(customer.getName());
}
}


A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location). The location is a URL and you can generate such a URL from an FXML resource by:



new FXMLLoader(getClass().getResource("sample.fxml"));


Be careful NOT to use a static load function on the FXMLLoader, or you will not be able to get your controller from your loader instance.



FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:




  1. Construct an FXMLLoader based upon fxml markup at a specified location

  2. Get a controller from the FXMLLoader instance.

  3. Invoke methods on the retrieved controller to provide the controller with references to the domain objects.


This blog (by another writer) provides an alternate, but similar, example.



Setting a Controller on the FXMLLoader



CustomerDialogController dialogController = 
new CustomerDialogController(param1, param2);

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

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


You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.



To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a fx:controller attribute in your fxml file.



Due to the limitation on the fx:controller definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.



Having the Controller Retrieve Parameters from an External Static Method



This method is exemplified by Sergey's answer to Javafx 2.0 How-to Application.getParameters() in a Controller.java file.



Use Dependency Injection



FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system. There is a sample of integrating FXML with the Spring dependency injection system (unfortunately the link is dead and the content is gone, if anybody knows of a similar example, please edit this question to reference it), though it's a bit clunkier than it would be using the new custom controller factory features made available in JavaFX 2.2.



A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.



Use an Event Bus



Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus for communication between FXML instantiated controllers and other application logic.




The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.




Follow-up Q&A




on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage




It is a functional solution to a problem. A stage is returned from the showCustomerDialog function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.





Additional information supplied by StackOverflow user named @dzim



Example for Spring Boot Dependency Injection



The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink.
The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE:
https://stackoverflow.com/a/36310391/1281217





Sometimes, you might want to pass results back to the caller, in which case you can check out the answer to the related question:




  • JavaFX FXML Parameter passing from Controller A to B and back






share|improve this answer



















  • 1




    the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."
    – j will
    Dec 6 '13 at 3:41








  • 1




    The DataFX Controller Frameworks provides some injection support for FXML controllers: guigarage.com/2013/12/datafx-controller-framework-preview
    – Hendrik Ebbers
    Mar 5 '14 at 14:11






  • 2




    +1 for the "Be careful NOT to use a static load function" Thank you so much jewelsea, you are great!
    – Martin Pfeffer
    May 22 '15 at 2:31






  • 2




    Added additional Q&A section to answer to address the further questions of @Anarkie
    – jewelsea
    Dec 29 '15 at 19:24








  • 3




    for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?
    – Zahan Safallwa
    Apr 24 '17 at 7:43




















up vote
8
down vote













javafx.scene.Node class has a pair of methods
setUserData(Object)
and
Object getUserData()



Which you could use to add your info to the Node.



So, you can call page.setUserData(info);



And controller can check, if info is set. Also, you could use ObjectProperty for back-forward data transfering, if needed.



Observe a documentation here:
http://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html
Before the phrase "In the first version, the handleButtonAction() is tagged with @FXML to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The initialize() method is similarly annotated."



So, you need to associate a controller with a node, and set a user data to the node.






share|improve this answer





















  • This might work! Can I get the node from the Stage?
    – Alvaro
    Jan 7 '13 at 1:51










  • Stage.getScene() -> Scene.getRoot() -> recursive search with Parent.getChildrenUnmodifiable(). This is very dirty way. If somebody could suggest smth better - that will be great.
    – Alexander Kirov
    Jan 7 '13 at 1:57












  • It seems Stage.getScene().getRoot() is the correct way! Thanks
    – Alvaro
    Jan 7 '13 at 2:10


















up vote
7
down vote













Here is an example for passing parameters to a fxml document through namespace.



<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1">
<BorderPane>
<center>
<Label text="$labelText"/>
</center>
</BorderPane>
</VBox>


Define value External Text for namespace variable labelText:



import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class NamespaceParameterExampleApplication extends Application {

public static void main(String args) {
launch(args);
}

@Override
public void start(Stage primaryStage) throws IOException {
final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("namespace-parameter-example.fxml"));

fxmlLoader.getNamespace()
.put("labelText", "External Text");

final Parent root = fxmlLoader.load();

primaryStage.setTitle("Namespace Parameter Example");
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
}





share|improve this answer





















  • It should be noted that some keys are used internally: e.g. FXMLLoader.CONTROLLER_KEYWORD, FXMLLoader.LOCATION_KEY, FXMLLoader.RESOURCES_KEY and any string used as value for the fx:id attribute.
    – fabian
    Feb 1 '16 at 22:55












  • Thank for this, my other scene is just a container that shows the text previously shown on my main scene. Now I can have one fxml that I can reuse in multiple places by initialiszing content via Namepace variables. I didnt' have to create any new methods or alter my constructor or initalisers - just addd variable in my FXML and add one line into my fxmloader code in the main controller.
    – SystemsInCode
    Oct 28 at 21:35




















up vote
6
down vote














I realize this is a very old post and has some great answers already,
but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.




In this example, we will use 5 files:





  1. Main.java - Simply used to start the application and call the first controller.


  2. Controller1.java - The controller for the first FXML layout.


  3. Controller2.java - The controller for the second FXML layout.


  4. Layout1.fxml - The FXML layout for the first scene.


  5. Layout2.fxml - The FXML layout for the second scene.


All files are listed in their entirety at the bottom of this post.



The Goal: To demonstrate passing values from Controller1 to Controller2 and vice versa.



The Program Flow:




  • The first scene contains a TextField, a Button, and a Label. When the Button is clicked, the second window is loaded and displayed, including the text entered in the TextField.

  • Within the second scene, there is also a TextField, a Button, and a Label. The Label will display the text entered in the TextField on the first scene.

  • Upon entering text in the second scene's TextField and clicking its Button, the first scene's Label is updated to show the entered text.


This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.



The code itself is also commented with some details of what is happening and how.




THE CODE




Main.java:



import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {

public static void main(String args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {

// Create the first controller, which loads Layout1.fxml within its own constructor
Controller1 controller1 = new Controller1();

// Show the new stage
controller1.showStage();

}
}


Controller1.java:



import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller1 {

// Holds this controller's Stage
private final Stage thisStage;

// Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
@FXML
private TextField txtToSecondController;
@FXML
private Button btnOpenLayout2;
@FXML
private Label lblFromController2;

public Controller1() {

// Create the new stage
thisStage = new Stage();

// Load the FXML file
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));

// Set this class as the controller
loader.setController(this);

// Load the scene
thisStage.setScene(new Scene(loader.load()));

// Setup the window/stage
thisStage.setTitle("Passing Controllers Example - Layout1");

} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Show the stage that was loaded in the constructor
*/
public void showStage() {
thisStage.showAndWait();
}

/**
* The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
*/
@FXML
private void initialize() {

// Add an action for the "Open Layout2" button
btnOpenLayout2.setOnAction(event -> openLayout2());
}

/**
* Performs the action of loading and showing Layout2
*/
private void openLayout2() {

// Create the second controller, which loads its own FXML file. We pass a reference to this controller
// using the keyword [this]; that allows the second controller to access the methods contained in here.
Controller2 controller2 = new Controller2(this);

// Show the new stage/window
controller2.showStage();

}

/**
* Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
*/
public String getEnteredText() {
return txtToSecondController.getText();
}

/**
* Allows other controllers to set the text of this layout's Label
*/
public void setTextFromController2(String text) {
lblFromController2.setText(text);
}
}


Controller2.java:



import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller2 {

// Holds this controller's Stage
private Stage thisStage;

// Will hold a reference to the first controller, allowing us to access the methods found there.
private final Controller1 controller1;

// Add references to the controls in Layout2.fxml
@FXML
private Label lblFromController1;
@FXML
private TextField txtToFirstController;
@FXML
private Button btnSetLayout1Text;

public Controller2(Controller1 controller1) {
// We received the first controller, now let's make it usable throughout this controller.
this.controller1 = controller1;

// Create the new stage
thisStage = new Stage();

// Load the FXML file
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));

// Set this class as the controller
loader.setController(this);

// Load the scene
thisStage.setScene(new Scene(loader.load()));

// Setup the window/stage
thisStage.setTitle("Passing Controllers Example - Layout2");

} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Show the stage that was loaded in the constructor
*/
public void showStage() {
thisStage.showAndWait();
}

@FXML
private void initialize() {

// Set the label to whatever the text entered on Layout1 is
lblFromController1.setText(controller1.getEnteredText());

// Set the action for the button
btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
}

/**
* Calls the "setTextFromController2()" method on the first controller to update its Label
*/
private void setTextOnLayout1() {
controller1.setTextFromController2(txtToFirstController.getText());
}

}


Layout1.fxml:



<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
<VBox alignment="CENTER" spacing="10.0">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
</padding>
<Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
<HBox alignment="CENTER_LEFT" spacing="10.0">
<Label text="Enter Text:"/>
<TextField fx:id="txtToSecondController"/>
<Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
</HBox>
<VBox alignment="CENTER">
<Label text="Text From Controller2:"/>
<Label fx:id="lblFromController2" text="Nothing Yet!"/>
</VBox>
</VBox>
</AnchorPane>


Layout2.fxml:



<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
<VBox alignment="CENTER" spacing="10.0">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
</padding>
<Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
<VBox alignment="CENTER">
<Label text="Text From Controller1:"/>
<Label fx:id="lblFromController1" text="Nothing Yet!"/>
</VBox>
<HBox alignment="CENTER_LEFT" spacing="10.0">
<Label text="Enter Text:"/>
<TextField fx:id="txtToFirstController"/>
<Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
</HBox>
</VBox>
</AnchorPane>





share|improve this answer























  • Is it possible to set the controller in the FXML file? Beause removing the line: loader.setController(this) and adding the controller in the FXML file crashes the application
    – Halfacht
    Oct 20 at 10:15








  • 1




    Not if the FXML is loaded from within the controller itself. If you load the FXML from the Main class, for example, you can define the controller in the FXML file and get a reference to it using loader.getController()
    – Zephyr
    Oct 20 at 12:52


















up vote
3
down vote













This WORKS ..



Remember first time you print the passing value you will get null,
You can use it after your windows loaded , same for everything you want to code for any other component.




First Controller




try {
Stage st = new Stage();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/inty360/free/form/MainOnline.fxml"));

Parent sceneMain = loader.load();

MainOnlineController controller = loader.<MainOnlineController>getController();
controller.initVariable(99L);

Scene scene = new Scene(sceneMain);
st.setScene(scene);
st.setMaximized(true);
st.setTitle("My App");
st.show();
} catch (IOException ex) {
Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
}



Another Controller




public void initVariable(Long id_usuario){
this.id_usuario = id_usuario;
label_usuario_nombre.setText(id_usuario.toString());

}





share|improve this answer





















  • This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
    – Menai Ala Eddine
    Sep 18 '17 at 23:15










  • @XlintXms see the related question JavaFX FXML Parameter passing from Controller A to B and back, which addresses your additional question.
    – jewelsea
    Jan 11 at 23:13


















up vote
2
down vote













You have to create one Context Class.



public class Context {
private final static Context instance = new Context();
public static Context getInstance() {
return instance;
}

private Connection con;
public void setConnection(Connection con)
{
this.con=con;
}
public Connection getConnection() {
return con;
}

private TabRoughController tabRough;
public void setTabRough(TabRoughController tabRough) {
this.tabRough=tabRough;
}

public TabRoughController getTabRough() {
return tabRough;
}
}


You have to just set instance of controller in initialization using



Context.getInstance().setTabRough(this);


and you can use it from your whole application just using



TabRoughController cont=Context.getInstance().getTabRough();


Now you can pass parameter to any controller from whole application.






share|improve this answer




























    up vote
    0
    down vote













    Here is an example for using a controller injected by Guice.



    /**
    * Loads a FXML file and injects its controller from the given Guice {@code Provider}
    */
    public abstract class GuiceFxmlLoader {

    public GuiceFxmlLoader(Stage stage, Provider<?> provider) {
    mStage = Objects.requireNonNull(stage);
    mProvider = Objects.requireNonNull(provider);
    }

    /**
    * @return the FXML file name
    */
    public abstract String getFileName();

    /**
    * Load FXML, set its controller with given {@code Provider}, and add it to {@code Stage}.
    */
    public void loadView() {
    try {
    FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource(getFileName()));
    loader.setControllerFactory(p -> mProvider.get());
    Node view = loader.load();
    setViewInStage(view);
    }
    catch (IOException ex) {
    LOGGER.error("Failed to load FXML: " + getFileName(), ex);
    }
    }

    private void setViewInStage(Node view) {
    BorderPane pane = (BorderPane)mStage.getScene().getRoot();
    pane.setCenter(view);
    }

    private static final Logger LOGGER = Logger.getLogger(GuiceFxmlLoader.class);

    private final Stage mStage;
    private final Provider<?> mProvider;
    }


    Here is a concrete implementation of the loader:



    public class ConcreteViewLoader extends GuiceFxmlLoader {

    @Inject
    public ConcreteViewLoader(Stage stage, Provider<MyController> provider) {
    super(stage, provider);
    }

    @Override
    public String getFileName() {
    return "my_view.fxml";
    }
    }


    Note this example loads the view into the center of a BoarderPane that is the root of the Scene in the Stage. This is irrelevant to the example (implementation detail of my specific use case) but decided to leave it in as some may find it useful.






    share|improve this answer




























      up vote
      0
      down vote













      You can decide to use a public observable list to store public data, or just create a public setter method to store data and retrieve from the corresponding controller






      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14187963%2fpassing-parameters-javafx-fxml%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        8 Answers
        8






        active

        oldest

        votes








        8 Answers
        8






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        226
        down vote



        accepted










        Recommended Approach



        This answer enumerates different mechanisms for passing parameters to FXML controllers.



        For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.



        For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.



        Passing Parameters Directly From the Caller to the Controller



        Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.



        Something like the following code:



        public Stage showCustomerDialog(Customer customer) {
        FXMLLoader loader = new FXMLLoader(
        getClass().getResource(
        "customerDialog.fxml"
        )
        );

        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(
        new Scene(
        (Pane) loader.load()
        )
        );

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

        stage.show();

        return stage;
        }

        ...

        class CustomerDialogController {
        @FXML private Label customerName;
        void initialize() {}
        void initData(Customer customer) {
        customerName.setText(customer.getName());
        }
        }


        A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location). The location is a URL and you can generate such a URL from an FXML resource by:



        new FXMLLoader(getClass().getResource("sample.fxml"));


        Be careful NOT to use a static load function on the FXMLLoader, or you will not be able to get your controller from your loader instance.



        FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:




        1. Construct an FXMLLoader based upon fxml markup at a specified location

        2. Get a controller from the FXMLLoader instance.

        3. Invoke methods on the retrieved controller to provide the controller with references to the domain objects.


        This blog (by another writer) provides an alternate, but similar, example.



        Setting a Controller on the FXMLLoader



        CustomerDialogController dialogController = 
        new CustomerDialogController(param1, param2);

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

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


        You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.



        To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a fx:controller attribute in your fxml file.



        Due to the limitation on the fx:controller definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.



        Having the Controller Retrieve Parameters from an External Static Method



        This method is exemplified by Sergey's answer to Javafx 2.0 How-to Application.getParameters() in a Controller.java file.



        Use Dependency Injection



        FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system. There is a sample of integrating FXML with the Spring dependency injection system (unfortunately the link is dead and the content is gone, if anybody knows of a similar example, please edit this question to reference it), though it's a bit clunkier than it would be using the new custom controller factory features made available in JavaFX 2.2.



        A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.



        Use an Event Bus



        Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus for communication between FXML instantiated controllers and other application logic.




        The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.




        Follow-up Q&A




        on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage




        It is a functional solution to a problem. A stage is returned from the showCustomerDialog function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.





        Additional information supplied by StackOverflow user named @dzim



        Example for Spring Boot Dependency Injection



        The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink.
        The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE:
        https://stackoverflow.com/a/36310391/1281217





        Sometimes, you might want to pass results back to the caller, in which case you can check out the answer to the related question:




        • JavaFX FXML Parameter passing from Controller A to B and back






        share|improve this answer



















        • 1




          the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."
          – j will
          Dec 6 '13 at 3:41








        • 1




          The DataFX Controller Frameworks provides some injection support for FXML controllers: guigarage.com/2013/12/datafx-controller-framework-preview
          – Hendrik Ebbers
          Mar 5 '14 at 14:11






        • 2




          +1 for the "Be careful NOT to use a static load function" Thank you so much jewelsea, you are great!
          – Martin Pfeffer
          May 22 '15 at 2:31






        • 2




          Added additional Q&A section to answer to address the further questions of @Anarkie
          – jewelsea
          Dec 29 '15 at 19:24








        • 3




          for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?
          – Zahan Safallwa
          Apr 24 '17 at 7:43

















        up vote
        226
        down vote



        accepted










        Recommended Approach



        This answer enumerates different mechanisms for passing parameters to FXML controllers.



        For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.



        For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.



        Passing Parameters Directly From the Caller to the Controller



        Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.



        Something like the following code:



        public Stage showCustomerDialog(Customer customer) {
        FXMLLoader loader = new FXMLLoader(
        getClass().getResource(
        "customerDialog.fxml"
        )
        );

        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(
        new Scene(
        (Pane) loader.load()
        )
        );

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

        stage.show();

        return stage;
        }

        ...

        class CustomerDialogController {
        @FXML private Label customerName;
        void initialize() {}
        void initData(Customer customer) {
        customerName.setText(customer.getName());
        }
        }


        A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location). The location is a URL and you can generate such a URL from an FXML resource by:



        new FXMLLoader(getClass().getResource("sample.fxml"));


        Be careful NOT to use a static load function on the FXMLLoader, or you will not be able to get your controller from your loader instance.



        FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:




        1. Construct an FXMLLoader based upon fxml markup at a specified location

        2. Get a controller from the FXMLLoader instance.

        3. Invoke methods on the retrieved controller to provide the controller with references to the domain objects.


        This blog (by another writer) provides an alternate, but similar, example.



        Setting a Controller on the FXMLLoader



        CustomerDialogController dialogController = 
        new CustomerDialogController(param1, param2);

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

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


        You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.



        To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a fx:controller attribute in your fxml file.



        Due to the limitation on the fx:controller definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.



        Having the Controller Retrieve Parameters from an External Static Method



        This method is exemplified by Sergey's answer to Javafx 2.0 How-to Application.getParameters() in a Controller.java file.



        Use Dependency Injection



        FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system. There is a sample of integrating FXML with the Spring dependency injection system (unfortunately the link is dead and the content is gone, if anybody knows of a similar example, please edit this question to reference it), though it's a bit clunkier than it would be using the new custom controller factory features made available in JavaFX 2.2.



        A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.



        Use an Event Bus



        Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus for communication between FXML instantiated controllers and other application logic.




        The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.




        Follow-up Q&A




        on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage




        It is a functional solution to a problem. A stage is returned from the showCustomerDialog function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.





        Additional information supplied by StackOverflow user named @dzim



        Example for Spring Boot Dependency Injection



        The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink.
        The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE:
        https://stackoverflow.com/a/36310391/1281217





        Sometimes, you might want to pass results back to the caller, in which case you can check out the answer to the related question:




        • JavaFX FXML Parameter passing from Controller A to B and back






        share|improve this answer



















        • 1




          the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."
          – j will
          Dec 6 '13 at 3:41








        • 1




          The DataFX Controller Frameworks provides some injection support for FXML controllers: guigarage.com/2013/12/datafx-controller-framework-preview
          – Hendrik Ebbers
          Mar 5 '14 at 14:11






        • 2




          +1 for the "Be careful NOT to use a static load function" Thank you so much jewelsea, you are great!
          – Martin Pfeffer
          May 22 '15 at 2:31






        • 2




          Added additional Q&A section to answer to address the further questions of @Anarkie
          – jewelsea
          Dec 29 '15 at 19:24








        • 3




          for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?
          – Zahan Safallwa
          Apr 24 '17 at 7:43















        up vote
        226
        down vote



        accepted







        up vote
        226
        down vote



        accepted






        Recommended Approach



        This answer enumerates different mechanisms for passing parameters to FXML controllers.



        For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.



        For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.



        Passing Parameters Directly From the Caller to the Controller



        Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.



        Something like the following code:



        public Stage showCustomerDialog(Customer customer) {
        FXMLLoader loader = new FXMLLoader(
        getClass().getResource(
        "customerDialog.fxml"
        )
        );

        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(
        new Scene(
        (Pane) loader.load()
        )
        );

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

        stage.show();

        return stage;
        }

        ...

        class CustomerDialogController {
        @FXML private Label customerName;
        void initialize() {}
        void initData(Customer customer) {
        customerName.setText(customer.getName());
        }
        }


        A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location). The location is a URL and you can generate such a URL from an FXML resource by:



        new FXMLLoader(getClass().getResource("sample.fxml"));


        Be careful NOT to use a static load function on the FXMLLoader, or you will not be able to get your controller from your loader instance.



        FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:




        1. Construct an FXMLLoader based upon fxml markup at a specified location

        2. Get a controller from the FXMLLoader instance.

        3. Invoke methods on the retrieved controller to provide the controller with references to the domain objects.


        This blog (by another writer) provides an alternate, but similar, example.



        Setting a Controller on the FXMLLoader



        CustomerDialogController dialogController = 
        new CustomerDialogController(param1, param2);

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

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


        You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.



        To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a fx:controller attribute in your fxml file.



        Due to the limitation on the fx:controller definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.



        Having the Controller Retrieve Parameters from an External Static Method



        This method is exemplified by Sergey's answer to Javafx 2.0 How-to Application.getParameters() in a Controller.java file.



        Use Dependency Injection



        FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system. There is a sample of integrating FXML with the Spring dependency injection system (unfortunately the link is dead and the content is gone, if anybody knows of a similar example, please edit this question to reference it), though it's a bit clunkier than it would be using the new custom controller factory features made available in JavaFX 2.2.



        A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.



        Use an Event Bus



        Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus for communication between FXML instantiated controllers and other application logic.




        The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.




        Follow-up Q&A




        on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage




        It is a functional solution to a problem. A stage is returned from the showCustomerDialog function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.





        Additional information supplied by StackOverflow user named @dzim



        Example for Spring Boot Dependency Injection



        The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink.
        The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE:
        https://stackoverflow.com/a/36310391/1281217





        Sometimes, you might want to pass results back to the caller, in which case you can check out the answer to the related question:




        • JavaFX FXML Parameter passing from Controller A to B and back






        share|improve this answer














        Recommended Approach



        This answer enumerates different mechanisms for passing parameters to FXML controllers.



        For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.



        For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.



        Passing Parameters Directly From the Caller to the Controller



        Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.



        Something like the following code:



        public Stage showCustomerDialog(Customer customer) {
        FXMLLoader loader = new FXMLLoader(
        getClass().getResource(
        "customerDialog.fxml"
        )
        );

        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(
        new Scene(
        (Pane) loader.load()
        )
        );

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

        stage.show();

        return stage;
        }

        ...

        class CustomerDialogController {
        @FXML private Label customerName;
        void initialize() {}
        void initData(Customer customer) {
        customerName.setText(customer.getName());
        }
        }


        A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location). The location is a URL and you can generate such a URL from an FXML resource by:



        new FXMLLoader(getClass().getResource("sample.fxml"));


        Be careful NOT to use a static load function on the FXMLLoader, or you will not be able to get your controller from your loader instance.



        FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:




        1. Construct an FXMLLoader based upon fxml markup at a specified location

        2. Get a controller from the FXMLLoader instance.

        3. Invoke methods on the retrieved controller to provide the controller with references to the domain objects.


        This blog (by another writer) provides an alternate, but similar, example.



        Setting a Controller on the FXMLLoader



        CustomerDialogController dialogController = 
        new CustomerDialogController(param1, param2);

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

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


        You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.



        To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a fx:controller attribute in your fxml file.



        Due to the limitation on the fx:controller definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.



        Having the Controller Retrieve Parameters from an External Static Method



        This method is exemplified by Sergey's answer to Javafx 2.0 How-to Application.getParameters() in a Controller.java file.



        Use Dependency Injection



        FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system. There is a sample of integrating FXML with the Spring dependency injection system (unfortunately the link is dead and the content is gone, if anybody knows of a similar example, please edit this question to reference it), though it's a bit clunkier than it would be using the new custom controller factory features made available in JavaFX 2.2.



        A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.



        Use an Event Bus



        Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus for communication between FXML instantiated controllers and other application logic.




        The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.




        Follow-up Q&A




        on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage




        It is a functional solution to a problem. A stage is returned from the showCustomerDialog function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.





        Additional information supplied by StackOverflow user named @dzim



        Example for Spring Boot Dependency Injection



        The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink.
        The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE:
        https://stackoverflow.com/a/36310391/1281217





        Sometimes, you might want to pass results back to the caller, in which case you can check out the answer to the related question:




        • JavaFX FXML Parameter passing from Controller A to B and back







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 11 at 23:18

























        answered Jan 7 '13 at 5:19









        jewelsea

        109k8255308




        109k8255308








        • 1




          the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."
          – j will
          Dec 6 '13 at 3:41








        • 1




          The DataFX Controller Frameworks provides some injection support for FXML controllers: guigarage.com/2013/12/datafx-controller-framework-preview
          – Hendrik Ebbers
          Mar 5 '14 at 14:11






        • 2




          +1 for the "Be careful NOT to use a static load function" Thank you so much jewelsea, you are great!
          – Martin Pfeffer
          May 22 '15 at 2:31






        • 2




          Added additional Q&A section to answer to address the further questions of @Anarkie
          – jewelsea
          Dec 29 '15 at 19:24








        • 3




          for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?
          – Zahan Safallwa
          Apr 24 '17 at 7:43
















        • 1




          the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."
          – j will
          Dec 6 '13 at 3:41








        • 1




          The DataFX Controller Frameworks provides some injection support for FXML controllers: guigarage.com/2013/12/datafx-controller-framework-preview
          – Hendrik Ebbers
          Mar 5 '14 at 14:11






        • 2




          +1 for the "Be careful NOT to use a static load function" Thank you so much jewelsea, you are great!
          – Martin Pfeffer
          May 22 '15 at 2:31






        • 2




          Added additional Q&A section to answer to address the further questions of @Anarkie
          – jewelsea
          Dec 29 '15 at 19:24








        • 3




          for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?
          – Zahan Safallwa
          Apr 24 '17 at 7:43










        1




        1




        the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."
        – j will
        Dec 6 '13 at 3:41






        the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."
        – j will
        Dec 6 '13 at 3:41






        1




        1




        The DataFX Controller Frameworks provides some injection support for FXML controllers: guigarage.com/2013/12/datafx-controller-framework-preview
        – Hendrik Ebbers
        Mar 5 '14 at 14:11




        The DataFX Controller Frameworks provides some injection support for FXML controllers: guigarage.com/2013/12/datafx-controller-framework-preview
        – Hendrik Ebbers
        Mar 5 '14 at 14:11




        2




        2




        +1 for the "Be careful NOT to use a static load function" Thank you so much jewelsea, you are great!
        – Martin Pfeffer
        May 22 '15 at 2:31




        +1 for the "Be careful NOT to use a static load function" Thank you so much jewelsea, you are great!
        – Martin Pfeffer
        May 22 '15 at 2:31




        2




        2




        Added additional Q&A section to answer to address the further questions of @Anarkie
        – jewelsea
        Dec 29 '15 at 19:24






        Added additional Q&A section to answer to address the further questions of @Anarkie
        – jewelsea
        Dec 29 '15 at 19:24






        3




        3




        for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?
        – Zahan Safallwa
        Apr 24 '17 at 7:43






        for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?
        – Zahan Safallwa
        Apr 24 '17 at 7:43














        up vote
        8
        down vote













        javafx.scene.Node class has a pair of methods
        setUserData(Object)
        and
        Object getUserData()



        Which you could use to add your info to the Node.



        So, you can call page.setUserData(info);



        And controller can check, if info is set. Also, you could use ObjectProperty for back-forward data transfering, if needed.



        Observe a documentation here:
        http://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html
        Before the phrase "In the first version, the handleButtonAction() is tagged with @FXML to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The initialize() method is similarly annotated."



        So, you need to associate a controller with a node, and set a user data to the node.






        share|improve this answer





















        • This might work! Can I get the node from the Stage?
          – Alvaro
          Jan 7 '13 at 1:51










        • Stage.getScene() -> Scene.getRoot() -> recursive search with Parent.getChildrenUnmodifiable(). This is very dirty way. If somebody could suggest smth better - that will be great.
          – Alexander Kirov
          Jan 7 '13 at 1:57












        • It seems Stage.getScene().getRoot() is the correct way! Thanks
          – Alvaro
          Jan 7 '13 at 2:10















        up vote
        8
        down vote













        javafx.scene.Node class has a pair of methods
        setUserData(Object)
        and
        Object getUserData()



        Which you could use to add your info to the Node.



        So, you can call page.setUserData(info);



        And controller can check, if info is set. Also, you could use ObjectProperty for back-forward data transfering, if needed.



        Observe a documentation here:
        http://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html
        Before the phrase "In the first version, the handleButtonAction() is tagged with @FXML to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The initialize() method is similarly annotated."



        So, you need to associate a controller with a node, and set a user data to the node.






        share|improve this answer





















        • This might work! Can I get the node from the Stage?
          – Alvaro
          Jan 7 '13 at 1:51










        • Stage.getScene() -> Scene.getRoot() -> recursive search with Parent.getChildrenUnmodifiable(). This is very dirty way. If somebody could suggest smth better - that will be great.
          – Alexander Kirov
          Jan 7 '13 at 1:57












        • It seems Stage.getScene().getRoot() is the correct way! Thanks
          – Alvaro
          Jan 7 '13 at 2:10













        up vote
        8
        down vote










        up vote
        8
        down vote









        javafx.scene.Node class has a pair of methods
        setUserData(Object)
        and
        Object getUserData()



        Which you could use to add your info to the Node.



        So, you can call page.setUserData(info);



        And controller can check, if info is set. Also, you could use ObjectProperty for back-forward data transfering, if needed.



        Observe a documentation here:
        http://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html
        Before the phrase "In the first version, the handleButtonAction() is tagged with @FXML to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The initialize() method is similarly annotated."



        So, you need to associate a controller with a node, and set a user data to the node.






        share|improve this answer












        javafx.scene.Node class has a pair of methods
        setUserData(Object)
        and
        Object getUserData()



        Which you could use to add your info to the Node.



        So, you can call page.setUserData(info);



        And controller can check, if info is set. Also, you could use ObjectProperty for back-forward data transfering, if needed.



        Observe a documentation here:
        http://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html
        Before the phrase "In the first version, the handleButtonAction() is tagged with @FXML to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The initialize() method is similarly annotated."



        So, you need to associate a controller with a node, and set a user data to the node.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 7 '13 at 0:02









        Alexander Kirov

        3,28511322




        3,28511322












        • This might work! Can I get the node from the Stage?
          – Alvaro
          Jan 7 '13 at 1:51










        • Stage.getScene() -> Scene.getRoot() -> recursive search with Parent.getChildrenUnmodifiable(). This is very dirty way. If somebody could suggest smth better - that will be great.
          – Alexander Kirov
          Jan 7 '13 at 1:57












        • It seems Stage.getScene().getRoot() is the correct way! Thanks
          – Alvaro
          Jan 7 '13 at 2:10


















        • This might work! Can I get the node from the Stage?
          – Alvaro
          Jan 7 '13 at 1:51










        • Stage.getScene() -> Scene.getRoot() -> recursive search with Parent.getChildrenUnmodifiable(). This is very dirty way. If somebody could suggest smth better - that will be great.
          – Alexander Kirov
          Jan 7 '13 at 1:57












        • It seems Stage.getScene().getRoot() is the correct way! Thanks
          – Alvaro
          Jan 7 '13 at 2:10
















        This might work! Can I get the node from the Stage?
        – Alvaro
        Jan 7 '13 at 1:51




        This might work! Can I get the node from the Stage?
        – Alvaro
        Jan 7 '13 at 1:51












        Stage.getScene() -> Scene.getRoot() -> recursive search with Parent.getChildrenUnmodifiable(). This is very dirty way. If somebody could suggest smth better - that will be great.
        – Alexander Kirov
        Jan 7 '13 at 1:57






        Stage.getScene() -> Scene.getRoot() -> recursive search with Parent.getChildrenUnmodifiable(). This is very dirty way. If somebody could suggest smth better - that will be great.
        – Alexander Kirov
        Jan 7 '13 at 1:57














        It seems Stage.getScene().getRoot() is the correct way! Thanks
        – Alvaro
        Jan 7 '13 at 2:10




        It seems Stage.getScene().getRoot() is the correct way! Thanks
        – Alvaro
        Jan 7 '13 at 2:10










        up vote
        7
        down vote













        Here is an example for passing parameters to a fxml document through namespace.



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.scene.control.Label?>
        <?import javafx.scene.layout.BorderPane?>
        <?import javafx.scene.layout.VBox?>
        <VBox xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1">
        <BorderPane>
        <center>
        <Label text="$labelText"/>
        </center>
        </BorderPane>
        </VBox>


        Define value External Text for namespace variable labelText:



        import javafx.application.Application;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Parent;
        import javafx.scene.Scene;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class NamespaceParameterExampleApplication extends Application {

        public static void main(String args) {
        launch(args);
        }

        @Override
        public void start(Stage primaryStage) throws IOException {
        final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("namespace-parameter-example.fxml"));

        fxmlLoader.getNamespace()
        .put("labelText", "External Text");

        final Parent root = fxmlLoader.load();

        primaryStage.setTitle("Namespace Parameter Example");
        primaryStage.setScene(new Scene(root, 400, 400));
        primaryStage.show();
        }
        }





        share|improve this answer





















        • It should be noted that some keys are used internally: e.g. FXMLLoader.CONTROLLER_KEYWORD, FXMLLoader.LOCATION_KEY, FXMLLoader.RESOURCES_KEY and any string used as value for the fx:id attribute.
          – fabian
          Feb 1 '16 at 22:55












        • Thank for this, my other scene is just a container that shows the text previously shown on my main scene. Now I can have one fxml that I can reuse in multiple places by initialiszing content via Namepace variables. I didnt' have to create any new methods or alter my constructor or initalisers - just addd variable in my FXML and add one line into my fxmloader code in the main controller.
          – SystemsInCode
          Oct 28 at 21:35

















        up vote
        7
        down vote













        Here is an example for passing parameters to a fxml document through namespace.



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.scene.control.Label?>
        <?import javafx.scene.layout.BorderPane?>
        <?import javafx.scene.layout.VBox?>
        <VBox xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1">
        <BorderPane>
        <center>
        <Label text="$labelText"/>
        </center>
        </BorderPane>
        </VBox>


        Define value External Text for namespace variable labelText:



        import javafx.application.Application;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Parent;
        import javafx.scene.Scene;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class NamespaceParameterExampleApplication extends Application {

        public static void main(String args) {
        launch(args);
        }

        @Override
        public void start(Stage primaryStage) throws IOException {
        final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("namespace-parameter-example.fxml"));

        fxmlLoader.getNamespace()
        .put("labelText", "External Text");

        final Parent root = fxmlLoader.load();

        primaryStage.setTitle("Namespace Parameter Example");
        primaryStage.setScene(new Scene(root, 400, 400));
        primaryStage.show();
        }
        }





        share|improve this answer





















        • It should be noted that some keys are used internally: e.g. FXMLLoader.CONTROLLER_KEYWORD, FXMLLoader.LOCATION_KEY, FXMLLoader.RESOURCES_KEY and any string used as value for the fx:id attribute.
          – fabian
          Feb 1 '16 at 22:55












        • Thank for this, my other scene is just a container that shows the text previously shown on my main scene. Now I can have one fxml that I can reuse in multiple places by initialiszing content via Namepace variables. I didnt' have to create any new methods or alter my constructor or initalisers - just addd variable in my FXML and add one line into my fxmloader code in the main controller.
          – SystemsInCode
          Oct 28 at 21:35















        up vote
        7
        down vote










        up vote
        7
        down vote









        Here is an example for passing parameters to a fxml document through namespace.



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.scene.control.Label?>
        <?import javafx.scene.layout.BorderPane?>
        <?import javafx.scene.layout.VBox?>
        <VBox xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1">
        <BorderPane>
        <center>
        <Label text="$labelText"/>
        </center>
        </BorderPane>
        </VBox>


        Define value External Text for namespace variable labelText:



        import javafx.application.Application;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Parent;
        import javafx.scene.Scene;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class NamespaceParameterExampleApplication extends Application {

        public static void main(String args) {
        launch(args);
        }

        @Override
        public void start(Stage primaryStage) throws IOException {
        final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("namespace-parameter-example.fxml"));

        fxmlLoader.getNamespace()
        .put("labelText", "External Text");

        final Parent root = fxmlLoader.load();

        primaryStage.setTitle("Namespace Parameter Example");
        primaryStage.setScene(new Scene(root, 400, 400));
        primaryStage.show();
        }
        }





        share|improve this answer












        Here is an example for passing parameters to a fxml document through namespace.



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.scene.control.Label?>
        <?import javafx.scene.layout.BorderPane?>
        <?import javafx.scene.layout.VBox?>
        <VBox xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1">
        <BorderPane>
        <center>
        <Label text="$labelText"/>
        </center>
        </BorderPane>
        </VBox>


        Define value External Text for namespace variable labelText:



        import javafx.application.Application;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Parent;
        import javafx.scene.Scene;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class NamespaceParameterExampleApplication extends Application {

        public static void main(String args) {
        launch(args);
        }

        @Override
        public void start(Stage primaryStage) throws IOException {
        final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("namespace-parameter-example.fxml"));

        fxmlLoader.getNamespace()
        .put("labelText", "External Text");

        final Parent root = fxmlLoader.load();

        primaryStage.setTitle("Namespace Parameter Example");
        primaryStage.setScene(new Scene(root, 400, 400));
        primaryStage.show();
        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 12 '16 at 4:05









        user1503636

        7314




        7314












        • It should be noted that some keys are used internally: e.g. FXMLLoader.CONTROLLER_KEYWORD, FXMLLoader.LOCATION_KEY, FXMLLoader.RESOURCES_KEY and any string used as value for the fx:id attribute.
          – fabian
          Feb 1 '16 at 22:55












        • Thank for this, my other scene is just a container that shows the text previously shown on my main scene. Now I can have one fxml that I can reuse in multiple places by initialiszing content via Namepace variables. I didnt' have to create any new methods or alter my constructor or initalisers - just addd variable in my FXML and add one line into my fxmloader code in the main controller.
          – SystemsInCode
          Oct 28 at 21:35




















        • It should be noted that some keys are used internally: e.g. FXMLLoader.CONTROLLER_KEYWORD, FXMLLoader.LOCATION_KEY, FXMLLoader.RESOURCES_KEY and any string used as value for the fx:id attribute.
          – fabian
          Feb 1 '16 at 22:55












        • Thank for this, my other scene is just a container that shows the text previously shown on my main scene. Now I can have one fxml that I can reuse in multiple places by initialiszing content via Namepace variables. I didnt' have to create any new methods or alter my constructor or initalisers - just addd variable in my FXML and add one line into my fxmloader code in the main controller.
          – SystemsInCode
          Oct 28 at 21:35


















        It should be noted that some keys are used internally: e.g. FXMLLoader.CONTROLLER_KEYWORD, FXMLLoader.LOCATION_KEY, FXMLLoader.RESOURCES_KEY and any string used as value for the fx:id attribute.
        – fabian
        Feb 1 '16 at 22:55






        It should be noted that some keys are used internally: e.g. FXMLLoader.CONTROLLER_KEYWORD, FXMLLoader.LOCATION_KEY, FXMLLoader.RESOURCES_KEY and any string used as value for the fx:id attribute.
        – fabian
        Feb 1 '16 at 22:55














        Thank for this, my other scene is just a container that shows the text previously shown on my main scene. Now I can have one fxml that I can reuse in multiple places by initialiszing content via Namepace variables. I didnt' have to create any new methods or alter my constructor or initalisers - just addd variable in my FXML and add one line into my fxmloader code in the main controller.
        – SystemsInCode
        Oct 28 at 21:35






        Thank for this, my other scene is just a container that shows the text previously shown on my main scene. Now I can have one fxml that I can reuse in multiple places by initialiszing content via Namepace variables. I didnt' have to create any new methods or alter my constructor or initalisers - just addd variable in my FXML and add one line into my fxmloader code in the main controller.
        – SystemsInCode
        Oct 28 at 21:35












        up vote
        6
        down vote














        I realize this is a very old post and has some great answers already,
        but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.




        In this example, we will use 5 files:





        1. Main.java - Simply used to start the application and call the first controller.


        2. Controller1.java - The controller for the first FXML layout.


        3. Controller2.java - The controller for the second FXML layout.


        4. Layout1.fxml - The FXML layout for the first scene.


        5. Layout2.fxml - The FXML layout for the second scene.


        All files are listed in their entirety at the bottom of this post.



        The Goal: To demonstrate passing values from Controller1 to Controller2 and vice versa.



        The Program Flow:




        • The first scene contains a TextField, a Button, and a Label. When the Button is clicked, the second window is loaded and displayed, including the text entered in the TextField.

        • Within the second scene, there is also a TextField, a Button, and a Label. The Label will display the text entered in the TextField on the first scene.

        • Upon entering text in the second scene's TextField and clicking its Button, the first scene's Label is updated to show the entered text.


        This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.



        The code itself is also commented with some details of what is happening and how.




        THE CODE




        Main.java:



        import javafx.application.Application;
        import javafx.stage.Stage;

        public class Main extends Application {

        public static void main(String args) {
        launch(args);
        }

        @Override
        public void start(Stage primaryStage) {

        // Create the first controller, which loads Layout1.fxml within its own constructor
        Controller1 controller1 = new Controller1();

        // Show the new stage
        controller1.showStage();

        }
        }


        Controller1.java:



        import javafx.fxml.FXML;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.Label;
        import javafx.scene.control.TextField;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class Controller1 {

        // Holds this controller's Stage
        private final Stage thisStage;

        // Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
        @FXML
        private TextField txtToSecondController;
        @FXML
        private Button btnOpenLayout2;
        @FXML
        private Label lblFromController2;

        public Controller1() {

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));

        // Set this class as the controller
        loader.setController(this);

        // Load the scene
        thisStage.setScene(new Scene(loader.load()));

        // Setup the window/stage
        thisStage.setTitle("Passing Controllers Example - Layout1");

        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        /**
        * Show the stage that was loaded in the constructor
        */
        public void showStage() {
        thisStage.showAndWait();
        }

        /**
        * The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
        */
        @FXML
        private void initialize() {

        // Add an action for the "Open Layout2" button
        btnOpenLayout2.setOnAction(event -> openLayout2());
        }

        /**
        * Performs the action of loading and showing Layout2
        */
        private void openLayout2() {

        // Create the second controller, which loads its own FXML file. We pass a reference to this controller
        // using the keyword [this]; that allows the second controller to access the methods contained in here.
        Controller2 controller2 = new Controller2(this);

        // Show the new stage/window
        controller2.showStage();

        }

        /**
        * Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
        */
        public String getEnteredText() {
        return txtToSecondController.getText();
        }

        /**
        * Allows other controllers to set the text of this layout's Label
        */
        public void setTextFromController2(String text) {
        lblFromController2.setText(text);
        }
        }


        Controller2.java:



        import javafx.fxml.FXML;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.Label;
        import javafx.scene.control.TextField;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class Controller2 {

        // Holds this controller's Stage
        private Stage thisStage;

        // Will hold a reference to the first controller, allowing us to access the methods found there.
        private final Controller1 controller1;

        // Add references to the controls in Layout2.fxml
        @FXML
        private Label lblFromController1;
        @FXML
        private TextField txtToFirstController;
        @FXML
        private Button btnSetLayout1Text;

        public Controller2(Controller1 controller1) {
        // We received the first controller, now let's make it usable throughout this controller.
        this.controller1 = controller1;

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));

        // Set this class as the controller
        loader.setController(this);

        // Load the scene
        thisStage.setScene(new Scene(loader.load()));

        // Setup the window/stage
        thisStage.setTitle("Passing Controllers Example - Layout2");

        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        /**
        * Show the stage that was loaded in the constructor
        */
        public void showStage() {
        thisStage.showAndWait();
        }

        @FXML
        private void initialize() {

        // Set the label to whatever the text entered on Layout1 is
        lblFromController1.setText(controller1.getEnteredText());

        // Set the action for the button
        btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
        }

        /**
        * Calls the "setTextFromController2()" method on the first controller to update its Label
        */
        private void setTextOnLayout1() {
        controller1.setTextFromController2(txtToFirstController.getText());
        }

        }


        Layout1.fxml:



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.geometry.Insets?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.AnchorPane?>
        <?import javafx.scene.layout.HBox?>
        <?import javafx.scene.layout.VBox?>
        <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
        <VBox alignment="CENTER" spacing="10.0">
        <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
        <Label text="Enter Text:"/>
        <TextField fx:id="txtToSecondController"/>
        <Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
        </HBox>
        <VBox alignment="CENTER">
        <Label text="Text From Controller2:"/>
        <Label fx:id="lblFromController2" text="Nothing Yet!"/>
        </VBox>
        </VBox>
        </AnchorPane>


        Layout2.fxml:



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.geometry.Insets?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.AnchorPane?>
        <?import javafx.scene.layout.HBox?>
        <?import javafx.scene.layout.VBox?>
        <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
        <VBox alignment="CENTER" spacing="10.0">
        <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
        <VBox alignment="CENTER">
        <Label text="Text From Controller1:"/>
        <Label fx:id="lblFromController1" text="Nothing Yet!"/>
        </VBox>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
        <Label text="Enter Text:"/>
        <TextField fx:id="txtToFirstController"/>
        <Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
        </HBox>
        </VBox>
        </AnchorPane>





        share|improve this answer























        • Is it possible to set the controller in the FXML file? Beause removing the line: loader.setController(this) and adding the controller in the FXML file crashes the application
          – Halfacht
          Oct 20 at 10:15








        • 1




          Not if the FXML is loaded from within the controller itself. If you load the FXML from the Main class, for example, you can define the controller in the FXML file and get a reference to it using loader.getController()
          – Zephyr
          Oct 20 at 12:52















        up vote
        6
        down vote














        I realize this is a very old post and has some great answers already,
        but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.




        In this example, we will use 5 files:





        1. Main.java - Simply used to start the application and call the first controller.


        2. Controller1.java - The controller for the first FXML layout.


        3. Controller2.java - The controller for the second FXML layout.


        4. Layout1.fxml - The FXML layout for the first scene.


        5. Layout2.fxml - The FXML layout for the second scene.


        All files are listed in their entirety at the bottom of this post.



        The Goal: To demonstrate passing values from Controller1 to Controller2 and vice versa.



        The Program Flow:




        • The first scene contains a TextField, a Button, and a Label. When the Button is clicked, the second window is loaded and displayed, including the text entered in the TextField.

        • Within the second scene, there is also a TextField, a Button, and a Label. The Label will display the text entered in the TextField on the first scene.

        • Upon entering text in the second scene's TextField and clicking its Button, the first scene's Label is updated to show the entered text.


        This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.



        The code itself is also commented with some details of what is happening and how.




        THE CODE




        Main.java:



        import javafx.application.Application;
        import javafx.stage.Stage;

        public class Main extends Application {

        public static void main(String args) {
        launch(args);
        }

        @Override
        public void start(Stage primaryStage) {

        // Create the first controller, which loads Layout1.fxml within its own constructor
        Controller1 controller1 = new Controller1();

        // Show the new stage
        controller1.showStage();

        }
        }


        Controller1.java:



        import javafx.fxml.FXML;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.Label;
        import javafx.scene.control.TextField;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class Controller1 {

        // Holds this controller's Stage
        private final Stage thisStage;

        // Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
        @FXML
        private TextField txtToSecondController;
        @FXML
        private Button btnOpenLayout2;
        @FXML
        private Label lblFromController2;

        public Controller1() {

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));

        // Set this class as the controller
        loader.setController(this);

        // Load the scene
        thisStage.setScene(new Scene(loader.load()));

        // Setup the window/stage
        thisStage.setTitle("Passing Controllers Example - Layout1");

        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        /**
        * Show the stage that was loaded in the constructor
        */
        public void showStage() {
        thisStage.showAndWait();
        }

        /**
        * The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
        */
        @FXML
        private void initialize() {

        // Add an action for the "Open Layout2" button
        btnOpenLayout2.setOnAction(event -> openLayout2());
        }

        /**
        * Performs the action of loading and showing Layout2
        */
        private void openLayout2() {

        // Create the second controller, which loads its own FXML file. We pass a reference to this controller
        // using the keyword [this]; that allows the second controller to access the methods contained in here.
        Controller2 controller2 = new Controller2(this);

        // Show the new stage/window
        controller2.showStage();

        }

        /**
        * Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
        */
        public String getEnteredText() {
        return txtToSecondController.getText();
        }

        /**
        * Allows other controllers to set the text of this layout's Label
        */
        public void setTextFromController2(String text) {
        lblFromController2.setText(text);
        }
        }


        Controller2.java:



        import javafx.fxml.FXML;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.Label;
        import javafx.scene.control.TextField;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class Controller2 {

        // Holds this controller's Stage
        private Stage thisStage;

        // Will hold a reference to the first controller, allowing us to access the methods found there.
        private final Controller1 controller1;

        // Add references to the controls in Layout2.fxml
        @FXML
        private Label lblFromController1;
        @FXML
        private TextField txtToFirstController;
        @FXML
        private Button btnSetLayout1Text;

        public Controller2(Controller1 controller1) {
        // We received the first controller, now let's make it usable throughout this controller.
        this.controller1 = controller1;

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));

        // Set this class as the controller
        loader.setController(this);

        // Load the scene
        thisStage.setScene(new Scene(loader.load()));

        // Setup the window/stage
        thisStage.setTitle("Passing Controllers Example - Layout2");

        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        /**
        * Show the stage that was loaded in the constructor
        */
        public void showStage() {
        thisStage.showAndWait();
        }

        @FXML
        private void initialize() {

        // Set the label to whatever the text entered on Layout1 is
        lblFromController1.setText(controller1.getEnteredText());

        // Set the action for the button
        btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
        }

        /**
        * Calls the "setTextFromController2()" method on the first controller to update its Label
        */
        private void setTextOnLayout1() {
        controller1.setTextFromController2(txtToFirstController.getText());
        }

        }


        Layout1.fxml:



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.geometry.Insets?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.AnchorPane?>
        <?import javafx.scene.layout.HBox?>
        <?import javafx.scene.layout.VBox?>
        <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
        <VBox alignment="CENTER" spacing="10.0">
        <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
        <Label text="Enter Text:"/>
        <TextField fx:id="txtToSecondController"/>
        <Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
        </HBox>
        <VBox alignment="CENTER">
        <Label text="Text From Controller2:"/>
        <Label fx:id="lblFromController2" text="Nothing Yet!"/>
        </VBox>
        </VBox>
        </AnchorPane>


        Layout2.fxml:



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.geometry.Insets?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.AnchorPane?>
        <?import javafx.scene.layout.HBox?>
        <?import javafx.scene.layout.VBox?>
        <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
        <VBox alignment="CENTER" spacing="10.0">
        <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
        <VBox alignment="CENTER">
        <Label text="Text From Controller1:"/>
        <Label fx:id="lblFromController1" text="Nothing Yet!"/>
        </VBox>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
        <Label text="Enter Text:"/>
        <TextField fx:id="txtToFirstController"/>
        <Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
        </HBox>
        </VBox>
        </AnchorPane>





        share|improve this answer























        • Is it possible to set the controller in the FXML file? Beause removing the line: loader.setController(this) and adding the controller in the FXML file crashes the application
          – Halfacht
          Oct 20 at 10:15








        • 1




          Not if the FXML is loaded from within the controller itself. If you load the FXML from the Main class, for example, you can define the controller in the FXML file and get a reference to it using loader.getController()
          – Zephyr
          Oct 20 at 12:52













        up vote
        6
        down vote










        up vote
        6
        down vote










        I realize this is a very old post and has some great answers already,
        but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.




        In this example, we will use 5 files:





        1. Main.java - Simply used to start the application and call the first controller.


        2. Controller1.java - The controller for the first FXML layout.


        3. Controller2.java - The controller for the second FXML layout.


        4. Layout1.fxml - The FXML layout for the first scene.


        5. Layout2.fxml - The FXML layout for the second scene.


        All files are listed in their entirety at the bottom of this post.



        The Goal: To demonstrate passing values from Controller1 to Controller2 and vice versa.



        The Program Flow:




        • The first scene contains a TextField, a Button, and a Label. When the Button is clicked, the second window is loaded and displayed, including the text entered in the TextField.

        • Within the second scene, there is also a TextField, a Button, and a Label. The Label will display the text entered in the TextField on the first scene.

        • Upon entering text in the second scene's TextField and clicking its Button, the first scene's Label is updated to show the entered text.


        This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.



        The code itself is also commented with some details of what is happening and how.




        THE CODE




        Main.java:



        import javafx.application.Application;
        import javafx.stage.Stage;

        public class Main extends Application {

        public static void main(String args) {
        launch(args);
        }

        @Override
        public void start(Stage primaryStage) {

        // Create the first controller, which loads Layout1.fxml within its own constructor
        Controller1 controller1 = new Controller1();

        // Show the new stage
        controller1.showStage();

        }
        }


        Controller1.java:



        import javafx.fxml.FXML;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.Label;
        import javafx.scene.control.TextField;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class Controller1 {

        // Holds this controller's Stage
        private final Stage thisStage;

        // Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
        @FXML
        private TextField txtToSecondController;
        @FXML
        private Button btnOpenLayout2;
        @FXML
        private Label lblFromController2;

        public Controller1() {

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));

        // Set this class as the controller
        loader.setController(this);

        // Load the scene
        thisStage.setScene(new Scene(loader.load()));

        // Setup the window/stage
        thisStage.setTitle("Passing Controllers Example - Layout1");

        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        /**
        * Show the stage that was loaded in the constructor
        */
        public void showStage() {
        thisStage.showAndWait();
        }

        /**
        * The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
        */
        @FXML
        private void initialize() {

        // Add an action for the "Open Layout2" button
        btnOpenLayout2.setOnAction(event -> openLayout2());
        }

        /**
        * Performs the action of loading and showing Layout2
        */
        private void openLayout2() {

        // Create the second controller, which loads its own FXML file. We pass a reference to this controller
        // using the keyword [this]; that allows the second controller to access the methods contained in here.
        Controller2 controller2 = new Controller2(this);

        // Show the new stage/window
        controller2.showStage();

        }

        /**
        * Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
        */
        public String getEnteredText() {
        return txtToSecondController.getText();
        }

        /**
        * Allows other controllers to set the text of this layout's Label
        */
        public void setTextFromController2(String text) {
        lblFromController2.setText(text);
        }
        }


        Controller2.java:



        import javafx.fxml.FXML;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.Label;
        import javafx.scene.control.TextField;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class Controller2 {

        // Holds this controller's Stage
        private Stage thisStage;

        // Will hold a reference to the first controller, allowing us to access the methods found there.
        private final Controller1 controller1;

        // Add references to the controls in Layout2.fxml
        @FXML
        private Label lblFromController1;
        @FXML
        private TextField txtToFirstController;
        @FXML
        private Button btnSetLayout1Text;

        public Controller2(Controller1 controller1) {
        // We received the first controller, now let's make it usable throughout this controller.
        this.controller1 = controller1;

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));

        // Set this class as the controller
        loader.setController(this);

        // Load the scene
        thisStage.setScene(new Scene(loader.load()));

        // Setup the window/stage
        thisStage.setTitle("Passing Controllers Example - Layout2");

        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        /**
        * Show the stage that was loaded in the constructor
        */
        public void showStage() {
        thisStage.showAndWait();
        }

        @FXML
        private void initialize() {

        // Set the label to whatever the text entered on Layout1 is
        lblFromController1.setText(controller1.getEnteredText());

        // Set the action for the button
        btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
        }

        /**
        * Calls the "setTextFromController2()" method on the first controller to update its Label
        */
        private void setTextOnLayout1() {
        controller1.setTextFromController2(txtToFirstController.getText());
        }

        }


        Layout1.fxml:



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.geometry.Insets?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.AnchorPane?>
        <?import javafx.scene.layout.HBox?>
        <?import javafx.scene.layout.VBox?>
        <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
        <VBox alignment="CENTER" spacing="10.0">
        <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
        <Label text="Enter Text:"/>
        <TextField fx:id="txtToSecondController"/>
        <Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
        </HBox>
        <VBox alignment="CENTER">
        <Label text="Text From Controller2:"/>
        <Label fx:id="lblFromController2" text="Nothing Yet!"/>
        </VBox>
        </VBox>
        </AnchorPane>


        Layout2.fxml:



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.geometry.Insets?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.AnchorPane?>
        <?import javafx.scene.layout.HBox?>
        <?import javafx.scene.layout.VBox?>
        <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
        <VBox alignment="CENTER" spacing="10.0">
        <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
        <VBox alignment="CENTER">
        <Label text="Text From Controller1:"/>
        <Label fx:id="lblFromController1" text="Nothing Yet!"/>
        </VBox>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
        <Label text="Enter Text:"/>
        <TextField fx:id="txtToFirstController"/>
        <Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
        </HBox>
        </VBox>
        </AnchorPane>





        share|improve this answer















        I realize this is a very old post and has some great answers already,
        but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.




        In this example, we will use 5 files:





        1. Main.java - Simply used to start the application and call the first controller.


        2. Controller1.java - The controller for the first FXML layout.


        3. Controller2.java - The controller for the second FXML layout.


        4. Layout1.fxml - The FXML layout for the first scene.


        5. Layout2.fxml - The FXML layout for the second scene.


        All files are listed in their entirety at the bottom of this post.



        The Goal: To demonstrate passing values from Controller1 to Controller2 and vice versa.



        The Program Flow:




        • The first scene contains a TextField, a Button, and a Label. When the Button is clicked, the second window is loaded and displayed, including the text entered in the TextField.

        • Within the second scene, there is also a TextField, a Button, and a Label. The Label will display the text entered in the TextField on the first scene.

        • Upon entering text in the second scene's TextField and clicking its Button, the first scene's Label is updated to show the entered text.


        This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.



        The code itself is also commented with some details of what is happening and how.




        THE CODE




        Main.java:



        import javafx.application.Application;
        import javafx.stage.Stage;

        public class Main extends Application {

        public static void main(String args) {
        launch(args);
        }

        @Override
        public void start(Stage primaryStage) {

        // Create the first controller, which loads Layout1.fxml within its own constructor
        Controller1 controller1 = new Controller1();

        // Show the new stage
        controller1.showStage();

        }
        }


        Controller1.java:



        import javafx.fxml.FXML;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.Label;
        import javafx.scene.control.TextField;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class Controller1 {

        // Holds this controller's Stage
        private final Stage thisStage;

        // Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
        @FXML
        private TextField txtToSecondController;
        @FXML
        private Button btnOpenLayout2;
        @FXML
        private Label lblFromController2;

        public Controller1() {

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));

        // Set this class as the controller
        loader.setController(this);

        // Load the scene
        thisStage.setScene(new Scene(loader.load()));

        // Setup the window/stage
        thisStage.setTitle("Passing Controllers Example - Layout1");

        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        /**
        * Show the stage that was loaded in the constructor
        */
        public void showStage() {
        thisStage.showAndWait();
        }

        /**
        * The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
        */
        @FXML
        private void initialize() {

        // Add an action for the "Open Layout2" button
        btnOpenLayout2.setOnAction(event -> openLayout2());
        }

        /**
        * Performs the action of loading and showing Layout2
        */
        private void openLayout2() {

        // Create the second controller, which loads its own FXML file. We pass a reference to this controller
        // using the keyword [this]; that allows the second controller to access the methods contained in here.
        Controller2 controller2 = new Controller2(this);

        // Show the new stage/window
        controller2.showStage();

        }

        /**
        * Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
        */
        public String getEnteredText() {
        return txtToSecondController.getText();
        }

        /**
        * Allows other controllers to set the text of this layout's Label
        */
        public void setTextFromController2(String text) {
        lblFromController2.setText(text);
        }
        }


        Controller2.java:



        import javafx.fxml.FXML;
        import javafx.fxml.FXMLLoader;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.control.Label;
        import javafx.scene.control.TextField;
        import javafx.stage.Stage;

        import java.io.IOException;

        public class Controller2 {

        // Holds this controller's Stage
        private Stage thisStage;

        // Will hold a reference to the first controller, allowing us to access the methods found there.
        private final Controller1 controller1;

        // Add references to the controls in Layout2.fxml
        @FXML
        private Label lblFromController1;
        @FXML
        private TextField txtToFirstController;
        @FXML
        private Button btnSetLayout1Text;

        public Controller2(Controller1 controller1) {
        // We received the first controller, now let's make it usable throughout this controller.
        this.controller1 = controller1;

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));

        // Set this class as the controller
        loader.setController(this);

        // Load the scene
        thisStage.setScene(new Scene(loader.load()));

        // Setup the window/stage
        thisStage.setTitle("Passing Controllers Example - Layout2");

        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        /**
        * Show the stage that was loaded in the constructor
        */
        public void showStage() {
        thisStage.showAndWait();
        }

        @FXML
        private void initialize() {

        // Set the label to whatever the text entered on Layout1 is
        lblFromController1.setText(controller1.getEnteredText());

        // Set the action for the button
        btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
        }

        /**
        * Calls the "setTextFromController2()" method on the first controller to update its Label
        */
        private void setTextOnLayout1() {
        controller1.setTextFromController2(txtToFirstController.getText());
        }

        }


        Layout1.fxml:



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.geometry.Insets?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.AnchorPane?>
        <?import javafx.scene.layout.HBox?>
        <?import javafx.scene.layout.VBox?>
        <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
        <VBox alignment="CENTER" spacing="10.0">
        <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
        <Label text="Enter Text:"/>
        <TextField fx:id="txtToSecondController"/>
        <Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
        </HBox>
        <VBox alignment="CENTER">
        <Label text="Text From Controller2:"/>
        <Label fx:id="lblFromController2" text="Nothing Yet!"/>
        </VBox>
        </VBox>
        </AnchorPane>


        Layout2.fxml:



        <?xml version="1.0" encoding="UTF-8"?>
        <?import javafx.geometry.Insets?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.AnchorPane?>
        <?import javafx.scene.layout.HBox?>
        <?import javafx.scene.layout.VBox?>
        <AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
        <VBox alignment="CENTER" spacing="10.0">
        <padding>
        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
        <VBox alignment="CENTER">
        <Label text="Text From Controller1:"/>
        <Label fx:id="lblFromController1" text="Nothing Yet!"/>
        </VBox>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
        <Label text="Enter Text:"/>
        <TextField fx:id="txtToFirstController"/>
        <Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
        </HBox>
        </VBox>
        </AnchorPane>






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jun 26 at 20:20

























        answered Jun 26 at 20:14









        Zephyr

        3,3942931




        3,3942931












        • Is it possible to set the controller in the FXML file? Beause removing the line: loader.setController(this) and adding the controller in the FXML file crashes the application
          – Halfacht
          Oct 20 at 10:15








        • 1




          Not if the FXML is loaded from within the controller itself. If you load the FXML from the Main class, for example, you can define the controller in the FXML file and get a reference to it using loader.getController()
          – Zephyr
          Oct 20 at 12:52


















        • Is it possible to set the controller in the FXML file? Beause removing the line: loader.setController(this) and adding the controller in the FXML file crashes the application
          – Halfacht
          Oct 20 at 10:15








        • 1




          Not if the FXML is loaded from within the controller itself. If you load the FXML from the Main class, for example, you can define the controller in the FXML file and get a reference to it using loader.getController()
          – Zephyr
          Oct 20 at 12:52
















        Is it possible to set the controller in the FXML file? Beause removing the line: loader.setController(this) and adding the controller in the FXML file crashes the application
        – Halfacht
        Oct 20 at 10:15






        Is it possible to set the controller in the FXML file? Beause removing the line: loader.setController(this) and adding the controller in the FXML file crashes the application
        – Halfacht
        Oct 20 at 10:15






        1




        1




        Not if the FXML is loaded from within the controller itself. If you load the FXML from the Main class, for example, you can define the controller in the FXML file and get a reference to it using loader.getController()
        – Zephyr
        Oct 20 at 12:52




        Not if the FXML is loaded from within the controller itself. If you load the FXML from the Main class, for example, you can define the controller in the FXML file and get a reference to it using loader.getController()
        – Zephyr
        Oct 20 at 12:52










        up vote
        3
        down vote













        This WORKS ..



        Remember first time you print the passing value you will get null,
        You can use it after your windows loaded , same for everything you want to code for any other component.




        First Controller




        try {
        Stage st = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/inty360/free/form/MainOnline.fxml"));

        Parent sceneMain = loader.load();

        MainOnlineController controller = loader.<MainOnlineController>getController();
        controller.initVariable(99L);

        Scene scene = new Scene(sceneMain);
        st.setScene(scene);
        st.setMaximized(true);
        st.setTitle("My App");
        st.show();
        } catch (IOException ex) {
        Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }



        Another Controller




        public void initVariable(Long id_usuario){
        this.id_usuario = id_usuario;
        label_usuario_nombre.setText(id_usuario.toString());

        }





        share|improve this answer





















        • This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
          – Menai Ala Eddine
          Sep 18 '17 at 23:15










        • @XlintXms see the related question JavaFX FXML Parameter passing from Controller A to B and back, which addresses your additional question.
          – jewelsea
          Jan 11 at 23:13















        up vote
        3
        down vote













        This WORKS ..



        Remember first time you print the passing value you will get null,
        You can use it after your windows loaded , same for everything you want to code for any other component.




        First Controller




        try {
        Stage st = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/inty360/free/form/MainOnline.fxml"));

        Parent sceneMain = loader.load();

        MainOnlineController controller = loader.<MainOnlineController>getController();
        controller.initVariable(99L);

        Scene scene = new Scene(sceneMain);
        st.setScene(scene);
        st.setMaximized(true);
        st.setTitle("My App");
        st.show();
        } catch (IOException ex) {
        Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }



        Another Controller




        public void initVariable(Long id_usuario){
        this.id_usuario = id_usuario;
        label_usuario_nombre.setText(id_usuario.toString());

        }





        share|improve this answer





















        • This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
          – Menai Ala Eddine
          Sep 18 '17 at 23:15










        • @XlintXms see the related question JavaFX FXML Parameter passing from Controller A to B and back, which addresses your additional question.
          – jewelsea
          Jan 11 at 23:13













        up vote
        3
        down vote










        up vote
        3
        down vote









        This WORKS ..



        Remember first time you print the passing value you will get null,
        You can use it after your windows loaded , same for everything you want to code for any other component.




        First Controller




        try {
        Stage st = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/inty360/free/form/MainOnline.fxml"));

        Parent sceneMain = loader.load();

        MainOnlineController controller = loader.<MainOnlineController>getController();
        controller.initVariable(99L);

        Scene scene = new Scene(sceneMain);
        st.setScene(scene);
        st.setMaximized(true);
        st.setTitle("My App");
        st.show();
        } catch (IOException ex) {
        Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }



        Another Controller




        public void initVariable(Long id_usuario){
        this.id_usuario = id_usuario;
        label_usuario_nombre.setText(id_usuario.toString());

        }





        share|improve this answer












        This WORKS ..



        Remember first time you print the passing value you will get null,
        You can use it after your windows loaded , same for everything you want to code for any other component.




        First Controller




        try {
        Stage st = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/inty360/free/form/MainOnline.fxml"));

        Parent sceneMain = loader.load();

        MainOnlineController controller = loader.<MainOnlineController>getController();
        controller.initVariable(99L);

        Scene scene = new Scene(sceneMain);
        st.setScene(scene);
        st.setMaximized(true);
        st.setTitle("My App");
        st.show();
        } catch (IOException ex) {
        Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }



        Another Controller




        public void initVariable(Long id_usuario){
        this.id_usuario = id_usuario;
        label_usuario_nombre.setText(id_usuario.toString());

        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 28 '16 at 22:25









        diego matos - keke

        1,175108




        1,175108












        • This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
          – Menai Ala Eddine
          Sep 18 '17 at 23:15










        • @XlintXms see the related question JavaFX FXML Parameter passing from Controller A to B and back, which addresses your additional question.
          – jewelsea
          Jan 11 at 23:13


















        • This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
          – Menai Ala Eddine
          Sep 18 '17 at 23:15










        • @XlintXms see the related question JavaFX FXML Parameter passing from Controller A to B and back, which addresses your additional question.
          – jewelsea
          Jan 11 at 23:13
















        This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
        – Menai Ala Eddine
        Sep 18 '17 at 23:15




        This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
        – Menai Ala Eddine
        Sep 18 '17 at 23:15












        @XlintXms see the related question JavaFX FXML Parameter passing from Controller A to B and back, which addresses your additional question.
        – jewelsea
        Jan 11 at 23:13




        @XlintXms see the related question JavaFX FXML Parameter passing from Controller A to B and back, which addresses your additional question.
        – jewelsea
        Jan 11 at 23:13










        up vote
        2
        down vote













        You have to create one Context Class.



        public class Context {
        private final static Context instance = new Context();
        public static Context getInstance() {
        return instance;
        }

        private Connection con;
        public void setConnection(Connection con)
        {
        this.con=con;
        }
        public Connection getConnection() {
        return con;
        }

        private TabRoughController tabRough;
        public void setTabRough(TabRoughController tabRough) {
        this.tabRough=tabRough;
        }

        public TabRoughController getTabRough() {
        return tabRough;
        }
        }


        You have to just set instance of controller in initialization using



        Context.getInstance().setTabRough(this);


        and you can use it from your whole application just using



        TabRoughController cont=Context.getInstance().getTabRough();


        Now you can pass parameter to any controller from whole application.






        share|improve this answer

























          up vote
          2
          down vote













          You have to create one Context Class.



          public class Context {
          private final static Context instance = new Context();
          public static Context getInstance() {
          return instance;
          }

          private Connection con;
          public void setConnection(Connection con)
          {
          this.con=con;
          }
          public Connection getConnection() {
          return con;
          }

          private TabRoughController tabRough;
          public void setTabRough(TabRoughController tabRough) {
          this.tabRough=tabRough;
          }

          public TabRoughController getTabRough() {
          return tabRough;
          }
          }


          You have to just set instance of controller in initialization using



          Context.getInstance().setTabRough(this);


          and you can use it from your whole application just using



          TabRoughController cont=Context.getInstance().getTabRough();


          Now you can pass parameter to any controller from whole application.






          share|improve this answer























            up vote
            2
            down vote










            up vote
            2
            down vote









            You have to create one Context Class.



            public class Context {
            private final static Context instance = new Context();
            public static Context getInstance() {
            return instance;
            }

            private Connection con;
            public void setConnection(Connection con)
            {
            this.con=con;
            }
            public Connection getConnection() {
            return con;
            }

            private TabRoughController tabRough;
            public void setTabRough(TabRoughController tabRough) {
            this.tabRough=tabRough;
            }

            public TabRoughController getTabRough() {
            return tabRough;
            }
            }


            You have to just set instance of controller in initialization using



            Context.getInstance().setTabRough(this);


            and you can use it from your whole application just using



            TabRoughController cont=Context.getInstance().getTabRough();


            Now you can pass parameter to any controller from whole application.






            share|improve this answer












            You have to create one Context Class.



            public class Context {
            private final static Context instance = new Context();
            public static Context getInstance() {
            return instance;
            }

            private Connection con;
            public void setConnection(Connection con)
            {
            this.con=con;
            }
            public Connection getConnection() {
            return con;
            }

            private TabRoughController tabRough;
            public void setTabRough(TabRoughController tabRough) {
            this.tabRough=tabRough;
            }

            public TabRoughController getTabRough() {
            return tabRough;
            }
            }


            You have to just set instance of controller in initialization using



            Context.getInstance().setTabRough(this);


            and you can use it from your whole application just using



            TabRoughController cont=Context.getInstance().getTabRough();


            Now you can pass parameter to any controller from whole application.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 22 '16 at 14:14









            CTN

            17717




            17717






















                up vote
                0
                down vote













                Here is an example for using a controller injected by Guice.



                /**
                * Loads a FXML file and injects its controller from the given Guice {@code Provider}
                */
                public abstract class GuiceFxmlLoader {

                public GuiceFxmlLoader(Stage stage, Provider<?> provider) {
                mStage = Objects.requireNonNull(stage);
                mProvider = Objects.requireNonNull(provider);
                }

                /**
                * @return the FXML file name
                */
                public abstract String getFileName();

                /**
                * Load FXML, set its controller with given {@code Provider}, and add it to {@code Stage}.
                */
                public void loadView() {
                try {
                FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource(getFileName()));
                loader.setControllerFactory(p -> mProvider.get());
                Node view = loader.load();
                setViewInStage(view);
                }
                catch (IOException ex) {
                LOGGER.error("Failed to load FXML: " + getFileName(), ex);
                }
                }

                private void setViewInStage(Node view) {
                BorderPane pane = (BorderPane)mStage.getScene().getRoot();
                pane.setCenter(view);
                }

                private static final Logger LOGGER = Logger.getLogger(GuiceFxmlLoader.class);

                private final Stage mStage;
                private final Provider<?> mProvider;
                }


                Here is a concrete implementation of the loader:



                public class ConcreteViewLoader extends GuiceFxmlLoader {

                @Inject
                public ConcreteViewLoader(Stage stage, Provider<MyController> provider) {
                super(stage, provider);
                }

                @Override
                public String getFileName() {
                return "my_view.fxml";
                }
                }


                Note this example loads the view into the center of a BoarderPane that is the root of the Scene in the Stage. This is irrelevant to the example (implementation detail of my specific use case) but decided to leave it in as some may find it useful.






                share|improve this answer

























                  up vote
                  0
                  down vote













                  Here is an example for using a controller injected by Guice.



                  /**
                  * Loads a FXML file and injects its controller from the given Guice {@code Provider}
                  */
                  public abstract class GuiceFxmlLoader {

                  public GuiceFxmlLoader(Stage stage, Provider<?> provider) {
                  mStage = Objects.requireNonNull(stage);
                  mProvider = Objects.requireNonNull(provider);
                  }

                  /**
                  * @return the FXML file name
                  */
                  public abstract String getFileName();

                  /**
                  * Load FXML, set its controller with given {@code Provider}, and add it to {@code Stage}.
                  */
                  public void loadView() {
                  try {
                  FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource(getFileName()));
                  loader.setControllerFactory(p -> mProvider.get());
                  Node view = loader.load();
                  setViewInStage(view);
                  }
                  catch (IOException ex) {
                  LOGGER.error("Failed to load FXML: " + getFileName(), ex);
                  }
                  }

                  private void setViewInStage(Node view) {
                  BorderPane pane = (BorderPane)mStage.getScene().getRoot();
                  pane.setCenter(view);
                  }

                  private static final Logger LOGGER = Logger.getLogger(GuiceFxmlLoader.class);

                  private final Stage mStage;
                  private final Provider<?> mProvider;
                  }


                  Here is a concrete implementation of the loader:



                  public class ConcreteViewLoader extends GuiceFxmlLoader {

                  @Inject
                  public ConcreteViewLoader(Stage stage, Provider<MyController> provider) {
                  super(stage, provider);
                  }

                  @Override
                  public String getFileName() {
                  return "my_view.fxml";
                  }
                  }


                  Note this example loads the view into the center of a BoarderPane that is the root of the Scene in the Stage. This is irrelevant to the example (implementation detail of my specific use case) but decided to leave it in as some may find it useful.






                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    Here is an example for using a controller injected by Guice.



                    /**
                    * Loads a FXML file and injects its controller from the given Guice {@code Provider}
                    */
                    public abstract class GuiceFxmlLoader {

                    public GuiceFxmlLoader(Stage stage, Provider<?> provider) {
                    mStage = Objects.requireNonNull(stage);
                    mProvider = Objects.requireNonNull(provider);
                    }

                    /**
                    * @return the FXML file name
                    */
                    public abstract String getFileName();

                    /**
                    * Load FXML, set its controller with given {@code Provider}, and add it to {@code Stage}.
                    */
                    public void loadView() {
                    try {
                    FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource(getFileName()));
                    loader.setControllerFactory(p -> mProvider.get());
                    Node view = loader.load();
                    setViewInStage(view);
                    }
                    catch (IOException ex) {
                    LOGGER.error("Failed to load FXML: " + getFileName(), ex);
                    }
                    }

                    private void setViewInStage(Node view) {
                    BorderPane pane = (BorderPane)mStage.getScene().getRoot();
                    pane.setCenter(view);
                    }

                    private static final Logger LOGGER = Logger.getLogger(GuiceFxmlLoader.class);

                    private final Stage mStage;
                    private final Provider<?> mProvider;
                    }


                    Here is a concrete implementation of the loader:



                    public class ConcreteViewLoader extends GuiceFxmlLoader {

                    @Inject
                    public ConcreteViewLoader(Stage stage, Provider<MyController> provider) {
                    super(stage, provider);
                    }

                    @Override
                    public String getFileName() {
                    return "my_view.fxml";
                    }
                    }


                    Note this example loads the view into the center of a BoarderPane that is the root of the Scene in the Stage. This is irrelevant to the example (implementation detail of my specific use case) but decided to leave it in as some may find it useful.






                    share|improve this answer












                    Here is an example for using a controller injected by Guice.



                    /**
                    * Loads a FXML file and injects its controller from the given Guice {@code Provider}
                    */
                    public abstract class GuiceFxmlLoader {

                    public GuiceFxmlLoader(Stage stage, Provider<?> provider) {
                    mStage = Objects.requireNonNull(stage);
                    mProvider = Objects.requireNonNull(provider);
                    }

                    /**
                    * @return the FXML file name
                    */
                    public abstract String getFileName();

                    /**
                    * Load FXML, set its controller with given {@code Provider}, and add it to {@code Stage}.
                    */
                    public void loadView() {
                    try {
                    FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource(getFileName()));
                    loader.setControllerFactory(p -> mProvider.get());
                    Node view = loader.load();
                    setViewInStage(view);
                    }
                    catch (IOException ex) {
                    LOGGER.error("Failed to load FXML: " + getFileName(), ex);
                    }
                    }

                    private void setViewInStage(Node view) {
                    BorderPane pane = (BorderPane)mStage.getScene().getRoot();
                    pane.setCenter(view);
                    }

                    private static final Logger LOGGER = Logger.getLogger(GuiceFxmlLoader.class);

                    private final Stage mStage;
                    private final Provider<?> mProvider;
                    }


                    Here is a concrete implementation of the loader:



                    public class ConcreteViewLoader extends GuiceFxmlLoader {

                    @Inject
                    public ConcreteViewLoader(Stage stage, Provider<MyController> provider) {
                    super(stage, provider);
                    }

                    @Override
                    public String getFileName() {
                    return "my_view.fxml";
                    }
                    }


                    Note this example loads the view into the center of a BoarderPane that is the root of the Scene in the Stage. This is irrelevant to the example (implementation detail of my specific use case) but decided to leave it in as some may find it useful.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 20 '15 at 0:48









                    jenglert

                    869820




                    869820






















                        up vote
                        0
                        down vote













                        You can decide to use a public observable list to store public data, or just create a public setter method to store data and retrieve from the corresponding controller






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          You can decide to use a public observable list to store public data, or just create a public setter method to store data and retrieve from the corresponding controller






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            You can decide to use a public observable list to store public data, or just create a public setter method to store data and retrieve from the corresponding controller






                            share|improve this answer












                            You can decide to use a public observable list to store public data, or just create a public setter method to store data and retrieve from the corresponding controller







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 15 at 12:29









                            Nospaniol Noah

                            92




                            92






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14187963%2fpassing-parameters-javafx-fxml%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Paul Cézanne

                                UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

                                Angular material date-picker (MatDatepicker) auto completes the date on focus out