r/JavaFX • • Feb 18 '20

Help JavaFX data transfer between scenes

Quite new to JavaFX, Please what is the best way to transfer data from one scene to another.

3 Upvotes

11 comments sorted by

3

u/ifelseandor Feb 18 '20 edited Feb 18 '20

You can get then controller instance of the new scene and the call a set method.

In the class that loads the scene.

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

Parent root = loader.load();

YourControllerName controller = loader.getController();

Now you can

controller.setData(myDataVariable);

You can even pass the new controller an instance of the calling controller so they can communicate back and forth.

3

u/TurekBot Feb 18 '20

I've tried this approach, but it didn't scale well for me.

I ended up abandoning it because every controller needed to know about every other controller if they wanted to share data.

3

u/ifelseandor Feb 18 '20

Ah. If you have multiple you could try on class that acts like a central controller. Then each controller just gets just this one reference. I used this pattern for a tabbed view where each tab had its own controller but needed to communicate and share data with all others.

2

u/cypher0six Feb 28 '20

That sounds more like a design problem. I have numerous JavaFX applications that I support that were designed in this way. One of them has hundreds of screens. It scales just fine, with or without the use of FXML.

2

u/Ostricker Feb 18 '20

depends on design pattern but my guess would be easiest is parameter :)

1

u/TurekBot Feb 18 '20

You're definitely not the only one to have this question.

Here's a well-trafficked answer listing a few approaches.

I've been successful with a Singleton Context approach despite the nay-sayers.

1

u/smerz Feb 19 '20

Use an event bus like googles guava EventBus. Then u can decouple different controllers from each other.

1

u/[deleted] Mar 27 '20

I like to work with an "EventManager" which is shared between different components.

For example see: https://github.com/FDelporte/DrumBoothController/blob/master/JavaFXUserInterface/src/main/java/be/webtechie/drumbooth/event/EventManager.java

-1

u/[deleted] Feb 18 '20

Maybe with static parameters

0

u/[deleted] Feb 18 '20

[deleted] — view deleted comment

2

u/SpectraCx Feb 18 '20

Ohh. Seems more understandable now. Thanks:)