I was just trying to find a simple and logical way to do just that. I do not have. It would be very nice if there was Application.getApplicationFor (AppClass.class) that managed some singles for you - but no.
If we limit the space of problems, it is quite easy to solve. If we make the class singleton, then this is a cake ... A simplified singleton template should work fine:
class MyApp extends Application { public static MyApp me; public MyApp() { me=this; } ... }
I may be null if it has not already been created by the system. You could protect more code from this.
... implementing code ...
Itβs just implemented - it seems to work (except for any strange situations with threads) I have a slightly different situation, I wedge the javaFX screen into the existing swing GUI. It works fine, but I need to make sure Application.launch is called only once. Adding this requirement, my final solution is this way:
(Sorry, but the syntax has a few 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 {
This controls the lock until Application.launch finishes instantiating the class, getting instances from other places, and ensuring that Application.launch is called exactly once, while getInstance is called at least once.
Bill k
source share