我有一个登录屏幕,我想将登录 ID 从 LoginController 传递给 MainController,所以我可以访问一些功能来更改密码等。
我这样加载 Controller :
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 绑定(bind)到 MainController.java。 有没有办法可以传递我需要的用户 ID,并在 Controller 的 initialize() 方法上访问它?
最佳答案
在使用 FXMLLoader 加载 Controller 后,可以在调用 show() 方法之前调用所述 Controller 的成员。必须获取对刚刚调用的 Controller 的引用并从那里调用 set() 方法(或直接访问属性,如果定义为 public)。
从示例中,我们假设与 Main.fxml 关联的 Controller 称为 MainController,并且 MainController 有一个 userId 属性,定义为 int。它的设置方法是setUser(int user)。所以,从 LoginController 类:
LoginController.java:
// User ID acquired from a textbox called txtUserId
int userId = Integer.parseInt(this.txtUserId.getText());
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/Main.fxml"));
Parent root = (Parent)fxmlLoader.load();
MainController controller = fxmlLoader.<MainController>getController();
controller.setUser(userId);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
MainController.java:
public void setUser(int userId){
this.userId = userId;
}
MainController.java:
//You may need this also if you're getting null
@FXML private void initialize() {
Platform.runLater(() -> {
//do stuff
});
}
关于java - 加载 FXML 时将参数传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14370183/