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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:29:57  来源:igfitidea点击:

How can I use a variable from another Controller in JavaFX

javacontrollerjavafx-2javafxviewcontroller

提问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 LoginManagerwhich has a reference to both the LoginControllerand the MainViewController.

设置 a LoginManager,它同时引用了LoginControllerMainViewController

  1. The loginManagercreates a login screen using the loginControllerand passes a reference to itself to the loginController.
  2. When login has passed, the loginControllernotifies the loginManagerof the login sessionID.
  3. The loginManagercan then create a MainViewController, passing the mainViewControllerthe sessionIDand replacing the scene contents with the main view.
  1. 使用 来loginManager创建登录屏幕loginController,并将对自身的引用传递给loginController
  2. 当登录通过时,loginController通知loginManager登录sessionID
  3. 所述loginManager然后可以创建MainViewController,传递mainViewControllersessionID和与主视图替换场景内容。

Here is a link to some sample codeto demonstrate this approach. login screenmainview screen

这是一些示例代码的链接,用于演示此方法。 登录画面主画面