JAVA FX:我可以从任何控制器访问在main中实例化的对象吗?

时间:2017-08-18 16:17:42

标签: java class javafx controller

我问的原因是要查明我是否可以在Main中实例化的类中保存身份验证详细信息,然后在各种控制器中引用它们?

public Class Identity(){
    Public String userId = null;
}

public Class Main extends Application(){
    Identity identity = new Identity;
    identity.userId = 123;
    //can I access this from any controller now?
    //I think that when i instantiate the object in a new controller the 
    //userId will again be null for that reference correct?
}

2 个答案:

答案 0 :(得分:-1)

您不能害怕,如果您在新控制器中实例化对象,则userId将为null,因为您引用新创建的对象的userId而不是原始对象。

最好的办法是使用数据库或文件保存数据并读取数据,这样任何控制器都可以访问数据。

答案 1 :(得分:-1)

你可以使用单一的设计模式。

    class App {

    private static App app;
    private Identity identity;

    private App() {
    }

    public static App app() {
        if (app == null)
            app = new App();
        return app;
    }


    public void setIdentity(Identity identity) {
        this.identity = identity;
    }

    public Identity getIdentity() {
        return identity;
    }

    class Identity {
        public String userId = null;

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getUserId() {
            return userId;
        }
    }
}




import static App.*;

public Class YourController {
    app().getIdentity();
}





import static App.*;
public Class Main extends Application(){
    Identity identity = new Identity;
    identity.userId = 123;
    app().setIdentiry(identity);

}