×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Sedrick Jefferson
Added: Mar 27, 2018 6:58 PM
Views: 6
JavaFx Pass Data Between Controllers
  1.  
  2. 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).
  3.  
  4. 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:
  5.  
  6. LoginController.java:
  7.      // User ID acquired from a textbox called txt_user_id
  8.         int user_id = Integer.parseInt(this.txt_user_id.getText());
  9.        
  10.         FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/Main.fxml"));    
  11.        
  12.         Parent root = (Parent)fxmlLoader.load();          
  13.         MainController controller = fxmlLoader.<MainController>getController();
  14.         controller.setUser(user_id);
  15.         Scene scene = new Scene(root);
  16.        
  17.         stage.setScene(scene);    
  18.        
  19.         stage.show();  
  20.  
  21.  
  22.        
  23. MainController.java:
  24.         public void setUser(int user_id){
  25.             this.user_id = user_id;
  26.         }