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
Suppose this is our JavaFX class:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; public class OKButton extends Application { @Override public void start(Stage stage) { Button btn = new Button("OK"); Scene scene = new Scene(btn, 200, 250); stage.setTitle("OK"); stage.setScene(scene); stage.show(); } }
Then we may launch it from another class like this:
import javafx.application.Application; public class Main { public static void main(String[] args) { Application.launch(OKButton.class, args); } }
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.
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