Getting application instance in javafx

How can I get an application instance when using javafx?

Usually you launch the application this way:

public class LoginForm { public static void main(String[] args) { LoginApplication.launch(LoginApplication.class, args); } } 

Running the method does not return an application instance. Is there any way to get an instance?

+7
java javafx
source share
2 answers

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 { // Have to run in a thread because launch doesn't return Application.launch(MyClass.class) } while(!instance) Thread.sleep(100) } return instance ... } // class 

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.

+3
source share

Typically, a javafx application uses a script to represent javafx and maps to a controller class that will invoke access to the fxml file:

 public class Main extends Application { @Override public void start(Stage stage) throws Exception { FXMLLoader myLoader = new FXMLLoader(getClass().getResource("/loginform.fxml")); Parent root = myLoader.load(); Scene scene = new Scene(root); stage.setScene(scene); stage.initStyle(StageStyle.DECORATED); stage.show(); } public static void main(String[] args) { Application.launch(args); } } 
-4
source share

All Articles