Shihab
Shihab

Reputation: 2679

JAVAFX: Passing data between FXML not Working

I've searched several times here for answer but didn't get my solution.

In my case: I want to take input from user and check validity. If everything is fine I will grab users ID from database and send that ID to another FXML and then run a select query there using that ID and display the results into a tableView.

In 2nd FXML (controller) I am using initialize() method to set data into tableView and a setId() method to receive user ID from previous FXML. But, initialize() method get called before setId() method and doesn't provide my required result as the ID is null.

Used Passing Parameters JavaFX FXML this method form passing data between FXML.

What will be the best solution for this?

FYI: Currently I'm using an extra class with static variable to store ID.

Upvotes: 0

Views: 424

Answers (1)

fabian
fabian

Reputation: 82461

You could use a controller factory that initializes the id before it returns the controller instance:

FXMLLoader loader = new FXMLLoader(url);
loader.setControllerFactory(c -> {
    MyController controller = new MyController();
    controller.setId(userId);
    return controller;
});
...
Node n = loader.load();

This way you could also use classes as controllers, that don't provide a default constructor. A more complex controller factory could be used to connect model and presenter (see MVP).

An alternative would be to modify the scene's contents in the setId method instead of the initialize method, which would be simpler than using a controller factory.

What the best solution is depends on your needs and personal preference. However, using a static member to pass data should be avoided, if possible.

Upvotes: 1

Related Questions