Consider a non-fx existing application, let's call it Business
.
Business
exposes a Model
object, which in turn exposes some properties. Model
also accepts listeners to those properties.
My question is about adding JavaFx gui to such application. The GuiApp
obviously extends javafx.application.Application
and will need a reference to a Model
object.
Searching for a solution for passing a non-String parameter to GuiApp
I found several different approaches :
- Static approach : for example have
Business
initialize a static reference toModel
inGuiApp
. One example of the use of statics can be seen here . - JavaFx 9 approach: as demonstrated here you can launch JavaFx application without extending
Application
. - Change workflow approach: change the existing workflow to have
GuiApp
initializeBussinessApp
. One example of such workflow can be seen here.
Are there another viable approaches ? Best practice ?
I'll try to demonstrate some different approaches for passing a reference between a java program, and a java-fx program.
I post it in hope it will help some future readers having similar need. I also hope it may encourage other answers with additional solutions.
The posted code should not be considered proper implementation, but rather a short code aiming to clarify the different approaches. For this purpose I'll introduce a simple listening interface :
A java class, that represents an exiting business application :
A java-fx application that should be added to the existing business application, listen to it and serve as view:
How do we share a reference, in this case a reference to
Observe
instance, between the two applications ?Approach 1: Consider the
start()
method as the entry point to the application (see James_D answer)This is simple and straight forward if you want to tie the existing java application with java-fx and use java-fx
Application
as the entry point:Approach 2: Use JavaFX 9 Platform#startup
This is the best solution I found, when you can not use the
Application#start
method as the entry point to the application.As demonstrated in fabians answer, as off java-fx 9 you can launch without extending
Application
. All you have to do is modify themain
of the java application:Approach 3: Use Static members
For example introduce a static getter in the java-fx application :
and use it in the java application:
A better approach to get a static reference might be (based on this answer) :