问题描述
我有一个登录界面,我想将登录ID从LoginController传递给MainController,所以我可以访问一些函数来更改密码等等。
I have a login screen, and I want to pass the login ID from the LoginController to the MainController, so I can access some functions to change password and whatnot.
我按如下方式加载控制器:
I load the controller like this:
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/Main.fxml"));
Parent root = (Parent)fxmlLoader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
Main.fxml受限于MainController.java。
有没有办法可以传递我需要的用户ID,并在控制器的initialize()方法上访问它?
Main.fxml is bounded to the MainController.java.Is there a way I can pass the user ID I need, and access it on the initialize() method of the controller?
推荐答案
使用FXMLLoader加载控制器后,可以在调用show()方法之前调用所述控制器的成员。必须获得刚刚调用的控制器的引用,并从那里调用set()方法(或直接访问属性,如果定义为public)。
After loading the controller with the FXMLLoader, it is possible to call for members of said controller before the show() method is invoked. One must get the reference to the controller just invoked and call a set() method from there (or access the attribute directly, if defined public).
从示例中,我们假设与Main.fxml关联的控制器称为MainController,MainController具有user_id属性,定义为int。它的set方法是setUser(int user)。所以,从LoginController类:
From the example, let us suppose that the controller associated with Main.fxml is called MainController, and MainController has a user_id attribute, defined as an int. Its set method is setUser(int user). So, from the LoginController class:
LoginController.java:
LoginController.java:
// User ID acquired from a textbox called txt_user_id
int user_id = Integer.parseInt(this.txt_user_id.getText());
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/Main.fxml"));
Parent root = (Parent)fxmlLoader.load();
MainController controller = fxmlLoader.<MainController>getController();
controller.setUser(user_id);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
MainController.java:
MainController.java:
public void setUser(int user_id){
this.user_id = user_id;
}
MainController.java:
MainController.java:
//You may need this also if you're getting null
@FXML private void initialize() {
Platform.runLater(() -> {
//do stuff
});
}
这篇关于加载FXML时将参数传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!