2

I am doing java fx and i got stuck into passing variable into different FXML scene. so on the first scene controller, LoginController is associated with Login.fxml

public class LoginController {

    @FXML private TextField username;
    @FXML private PasswordField password;
    @FXML private Button loginButton;
    @FXML private Label labelStatus;

    @FXML private void handleLoginButton() throws InterruptedException {

        try {
            FXMLLoader mainLoad = new FXMLLoader(getClass().getResource("../View/mainscreen.fxml"));
            Parent mainRoot = (Parent) mainLoad.load();
            Stage stage = new Stage();
            stage.setScene(new Scene(mainRoot));
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }
}

and when the new scene open i need to set the label based on the username variable that contains the user input. that means we need to pass variables from Login.fxml into mainscreen.fxml through controoler. How do i achieve this ?

Konz Mama
  • 975
  • 2
  • 8
  • 26

2 Answers2

2

The easiest way is to set proper fields in MainScreenController through setters. Yo can get controller that is responsible for this fxml by FXMLoader#getController() method ( https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.html#getController-- ).

Other ways depends of your application architecture. There should be an object that is responsible for storing that kind of information.

Mati
  • 2,476
  • 2
  • 17
  • 24
2

You can get next scene controller and pass variables

  FXMLLoader loader = new FXMLLoader(getClass().getResource("mainscreen.fxml"));
  MainScreenController controller = loader.getController();
  controller.setUserName(userName);