How can I get the application instance when using javafx?
Normally you launch an application this way:
public class LoginForm {
public static void main(String[] args) {
LoginApplication.launch(LoginApplication.class, args);
}
}
The method launch does not return an instance of application. Is there a way I could get the instance?
I was just trying to find an easy, logical way to do exactly this. I haven't. It would be really nice if there was an Application.getApplicationFor(AppClass.class) that managed some singletons for you--but no.
If we restrict the problem space it's pretty easy to solve. If we make the class a singleton, then it's cake... A simplified singleton pattern should work fine:
class MyApp extends Application
{
public static MyApp me;
public MyApp()
{
me=this;
}
...
}
me can be null if it hasn't been instantiated by the system yet. It would be possible to protect against that with more code.
... implementing code...
Just implemented this--seems to work (barring any strange threading situations) I have a slightly different situation, I'm wedging a javaFX screen into an existing swing GUI. It works fine, but I need to ensure that Application.launch is only called once. Adding this requirement, my final solution is thus:
(Sorry but the syntax has some groovy in it, should be easy for any Java user to translate)
class MyClass extends Application{
private static MyClass instance
public MyClass() {
instance=this
}
public synchronized static getInstance() {
if(!instance) {
Thread.start {
// Have to run in a thread because launch doesn't return
Application.launch(MyClass.class)
}
while(!instance)
Thread.sleep(100)
}
return instance
...
} // class
This manages blocking until Application.launch has completed instantiating the class, getting instances from other locations and ensuring that Application.launch gets called exactly once as long as getInstance has been called at least once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With