Search code examples
javafx-8

Launch JavaFX application from another class


I need to start a javafx Application from another "container" class and call functions on the Application, but there doesn't seem to be any way of getting hold of a reference to the Application started using the Application.launch() method. Is this possible? Thanks


Solution

  • I had the same problem as this and got round it using this hack:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;
    
    import java.util.concurrent.CountDownLatch;
    
    public class StartUpTest extends Application {
        public static final CountDownLatch latch = new CountDownLatch(1);
        public static StartUpTest startUpTest = null;
    
        public static StartUpTest waitForStartUpTest() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return startUpTest;
        }
    
        public static void setStartUpTest(StartUpTest startUpTest0) {
            startUpTest = startUpTest0;
            latch.countDown();
        }
    
        public StartUpTest() {
            setStartUpTest(this);
        }
    
        public void printSomething() {
            System.out.println("You called a method on the application");
        }
    
        @Override
        public void start(Stage stage) throws Exception {
            BorderPane pane = new BorderPane();
            Scene scene = new Scene(pane, 500, 500);
            stage.setScene(scene);
    
            Label label = new Label("Hello");
            pane.setCenter(label);
    
            stage.show();
        }
    
        public static void main(String[] args) {
            Application.launch(args);
        }
    }
    

    and then the class you are launching the application from:

    public class StartUpStartUpTest {
        public static void main(String[] args) {
            new Thread() {
                @Override
                public void run() {
                    javafx.application.Application.launch(StartUpTest.class);
                }
            }.start();
            StartUpTest startUpTest = StartUpTest.waitForStartUpTest();
            startUpTest.printSomething();
        }
    }
    

    Hope that helps you.