在JavaFX中获取应用程序实例 [英] Getting application instance in javafx

查看:77
本文介绍了在JavaFX中获取应用程序实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javafx时如何获取应用程序实例?

How can I get the application instance when using javafx?

通常,您以这种方式启动应用程序:

Normally you launch an application this way:

public class LoginForm {

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

}

方法启动不会返回应用程序的实例. 有没有办法获取实例?

The method launch does not return an instance of application. Is there a way I could get the instance?

推荐答案

我只是想找到一种简单,合乎逻辑的方法来做到这一点.我还没有如果有一个Application.getApplicationFor(AppClass.class)可以为您管理一些单例,那就太好了,但是没有.

I was just trying to find an easy, logical way to do exactly this. I haven't. It would be really nice if there was an Application.getApplicationFor(AppClass.class) that managed some singletons for you--but no.

如果我们限制问题空间,就很容易解决.如果我们将类设为单身人士,那就太简单了……简化的单身人士模式应该可以正常工作:

If we restrict the problem space it's pretty easy to solve. If we make the class a singleton, then it's cake... A simplified singleton pattern should work fine:

class MyApp extends Application
{           
    public static MyApp me;
    public MyApp()
    {
        me=this;
    }

    ... 
}

如果

me尚未被系统实例化,则可以为null.可能会有更多的代码来防止这种情况发生.

me can be null if it hasn't been instantiated by the system yet. It would be possible to protect against that with more code.

...实现代码...

... implementing code...

只需实施此操作-似乎可以正常工作(除非出现任何奇怪的线程情况) 我的情况略有不同,我将javaFX屏幕嵌入到现有的swing GUI中.它工作正常,但我需要确保Application.launch仅被调用一次.添加此要求后,我的最终解决方案是:

Just implemented this--seems to work (barring any strange threading situations) I have a slightly different situation, I'm wedging a javaFX screen into an existing swing GUI. It works fine, but I need to ensure that Application.launch is only called once. Adding this requirement, my final solution is thus:

(对不起,但语法有些古怪,任何Java用户都应该易于翻译)

(Sorry but the syntax has some 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

这将管理阻塞,直到Application.launch完成实例化该类,从其他位置获取实例并确保只要getInstance至少被调用一次,Application.launch就会被精确调用一次.

This manages blocking until Application.launch has completed instantiating the class, getting instances from other locations and ensuring that Application.launch gets called exactly once as long as getInstance has been called at least once.

这篇关于在JavaFX中获取应用程序实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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