我需要从另一个"容器"类启动一个javafx应用程序并在Application上调用函数,但是似乎没有任何方法可以获得对使用Application.launch()方法启动的Application的引用.这可能吗?谢谢
Thi*_*ark 40
假设这是我们的JavaFX类:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后我们可以从另一个类启动它,如下所示:
import javafx.application.Application;
public class Main {
public static void main(String[] args) {
Application.launch(OKButton.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
Boo*_*mah 20
我有同样的问题,并使用这个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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后是您从以下位置启动应用程序的类:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
希望对你有所帮助.