java 如何在 JavaFX 中使用来自另一个控制器的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14511016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use a variable from another Controller in JavaFX
提问by Victor Laerte
I have two scenes Login.fxml and MainView.fxml and two diferent controllers LoginController.java and MainViewControler.java
我有两个场景 Login.fxml 和 MainView.fxml 以及两个不同的控制器 LoginController.java 和 MainViewControler.java
In LoginController I do the whole process to login and get the value of JSessionID and store it in a object, like below:
在 LoginController 中,我完成了登录并获取 JSessionID 的值并将其存储在一个对象中的整个过程,如下所示:
loginGateway = loginGateway(gateway);
Now in MainViewController I need to use the this object (loginGateway) to getJSessionID and make other requests to the server. But how can I acess this object in another Controller Class (MainViewController.java) ????
现在在 MainViewController 中,我需要使用 this 对象(loginGateway)来获取 JSessionID 并向服务器发出其他请求。但是我怎样才能在另一个控制器类(MainViewController.java)中访问这个对象????
回答by jewelsea
Use a variation on the solution in Passing Parameters JavaFX FXML.
使用Passing Parameters JavaFX FXML 中解决方案的变体。
Setup a LoginManager
which has a reference to both the LoginController
and the MainViewController
.
设置 a LoginManager
,它同时引用了LoginController
和MainViewController
。
- The
loginManager
creates a login screen using theloginController
and passes a reference to itself to theloginController
. - When login has passed, the
loginController
notifies theloginManager
of the loginsessionID
. - The
loginManager
can then create aMainViewController
, passing themainViewController
thesessionID
and replacing the scene contents with the main view.
- 使用 来
loginManager
创建登录屏幕loginController
,并将对自身的引用传递给loginController
。 - 当登录通过时,
loginController
通知loginManager
登录sessionID
。 - 所述
loginManager
然后可以创建MainViewController
,传递mainViewController
的sessionID
和与主视图替换场景内容。
Here is a link to some sample codeto demonstrate this approach.
这是一些示例代码的链接,用于演示此方法。