2

I'm using JavaFX, where you create a class that extends JavaFX Application, and then you pass the class to JavaFX's launch method. Inside the Application class you override the start method which gets an instance of Stage passed into it.

How can I make this instance of Stage available as a dependency for other objects?

// Kotlin

fun main() {
    launch(MyApplication::class.java)
}

class MyApplication : Application()
{
    override fun start(stage: Stage)
    {
        // I want other objects to be able to have stage injected into them.
        val myWindow = MyWindow
        stage.run {
            scene = Scene(myWindow, 800.0, 600.0)
            show()
        }
    }
}

In Spring I think you would do something like this

// Java

Object externalyDefinedBean = ...;
GenericApplicationContext parentContext = new StaticApplicationContext();
parentContext.getBeanFactory().registerSingleton("injectedBean", externalyDefinedBean);
vbyzjnlehi
  • 307
  • 2
  • 15
  • 2
    Note that typically you don't need to provide the stage to other objects, as it's usually accessible via the scene graph from objects that are "naturally" available. E.g. in a JavaFX controller you have access to scene graph elements injected via `@FXML`, and you can always navigate from such a node via calls such as `node.getScene().getWindow()`. Injecting a `Stage` into other parts of your application is a bit of a code smell. – James_D Aug 01 '22 at 21:37
  • I know you can get stage in other ways, but this an example where I want to know how you would do it anyways. I don't have a better example for asking this question with regards to Dagger. – vbyzjnlehi Aug 01 '22 at 21:39
  • Fair enough; accessing the `HostServices`, for example, is a reason to need this. I don't know Dagger; I have seen this done in Spring and Guice. – James_D Aug 01 '22 at 21:40
  • 1
    There is a discussion of how to do something similar with Spring in [this answer](https://stackoverflow.com/questions/57887944/adding-spring-dependency-injection-in-javafx-jpa-repo-service/57896435#57896435), I also do not know the Dagger analog. The linked answer for Spring is a bit different in that it injects auto wired dependencies into the application rather than making the application an injectable managed bean (which I am not sure would be a good idea in any case). – jewelsea Aug 01 '22 at 23:58
  • 1
    [Gluon ignite](https://gluonhq.com/labs/ignite/) has a dagger implementation. You might want to check its source to see if it does what you want (I don't know if it will or not). – jewelsea Aug 02 '22 at 00:04

0 Answers0