在使用FXMLLoader加载控制器后,可以在调用show()方法之前调用所述控制器的成员.必须获得对调用的控制器的引用,并从那里调用set()方法(或直接访问属性,如果定义为public).
从示例中,我们假设与Main.fxml关联的控制器称为MainController,MainController具有一个定义为int的user_id属性.它的set方法是setUser(int user).所以,从LoginController类:
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.getController();
controller.setUser(user_id);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
MainController.java:
public void setUser(int user_id){
this.user_id = user_id;
}