从另一个类启动JavaFX应用程序 [英] Launch JavaFX application from another class

查看:125
本文介绍了从另一个类启动JavaFX应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从另一个容器"类启动javafx应用程序并在该应用程序上调用函数,但是似乎没有任何方法可以使用Application.launch()来获取对该应用程序的引用.方法.这可能吗? 谢谢

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

推荐答案

我遇到了与此相同的问题,并使用此hack解决了这个问题:

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();
    }
}

希望对您有帮助.

这篇关于从另一个类启动JavaFX应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆