简体   繁体   中英

How to pass the User object from one Controller to the different JavaFX Controller?

It's hard to explain, but I will try. I have a User object in scene #1 controller and I want this User to be passed to scene #2 controller. Here is the first Controller:

            @FXML
            private TextField password;
            @FXML
            private TextField username;
            private String id,pass;
            private User loginUser;

            DisplayController controller = new DisplayController();
            id = username.getText();
            pass = password.getText();
            loginUser = databaseStack.checkUser(id,pass);
            controller.passUser(loginUser);
            System.out.println(loginUser);
            Parent root = null;
            try {
                root = FXMLLoader.load(Main.class.getResource("javafx3.fxml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            Scene signUpScene = new Scene(root);
            Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
            window.setScene(signUpScene);
            window.show();

*databaseStack.checkUser() is the method in the different class that checks for a valid user; Here is the second Controller:

@FXML
private Button findFriend;
@FXML
private Label fullName;
@FXML
private Label eMail;
@FXML
private Label hobbies;
@FXML
private Label major;
private User loginUser;
public void initialize(){
    System.out.println(loginUser);
    findFriend.setStyle("-fx-background-color: \n" +
            "        linear-gradient(#ffd65b, #e68400),\n" +
            "        linear-gradient(#ffef84, #f2ba44),\n" +
            "        linear-gradient(#ffea6a, #efaa22),\n" +
            "        linear-gradient(#ffe657 0%, #f8c202 50%, #eea10b 100%),\n" +
            "        linear-gradient(from 0% 0% to 15% 50%, rgba(255,255,255,0.9), rgba(255,255,255,0));\n" +
            "    -fx-background-radius: 30;\n" +
            "    -fx-background-insets: 0,1,2,3,0;\n" +
            "    -fx-text-fill: #654b00;\n" +
            "    -fx-font-weight: bold;\n" +
            "    -fx-font-size: 20px;\n" +
            "    -fx-padding: 10 20 10 20;");
    findFriend.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            Parent root = null;
            try {
                root = FXMLLoader.load(Main.class.getResource("javafx4.fxml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            Scene signUpScene = new Scene(root);
            Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
            window.setScene(signUpScene);
            window.show();
        }
    });
}
public void passUser(User user){
    loginUser = user;
}

In controller 1 I pass the User "loginUser" to the passUser() method in the controller 2.In controller 2 in the method passUser() I set the private variable loginUser to the user that the method has received. Then I print out this User object in initialize(). But initialize() in controller 2 prints out "null" instead of the User that I have passed in passUser(). It probably happens because when I switch the scenes it resets all the variables. How do I fix it? How do I receive a User object that I passed to the local variable in passUser() method? Sorry for poor explanation, it's really hard to explain this problem for me. Thanks for your time and effort!

This is an example of direct communication between controllers.

public class ControllerA {
    @FXML
    private TextField usernameTextField;

    @FXML
    private Button loginButton;

    private Stage stage;

    @FXML
    private void initialize() {
        loginButton.setOnAction(event -> {
            try {
                FXMLLoader loader = new FXMLLoader(getClass().getResource("scene_2.fxml"));
                Parent parent = loader.load();

                ControllerB controllerB = loader.getController();
                controllerB.setUser(new User(usernameTextField.getText()));

                stage.setScene(new Scene(parent));

            }
            catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    public void setStage(Stage stage) {
        this.stage = stage;
    }
}

public class ControllerB {

    private User user;

    @FXML
    private Label wellcomeLabel;

    @FXML
    private void initialize() {

    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
        wellcomeLabel.setText("Wellcome " + user.getName());
    }
}

public class MainStage extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("scene_1.fxml"));
        Parent parent = loader.load();

        ControllerA controllerA = loader.getController();
        controllerA.setStage(primaryStage);

        primaryStage.setTitle("Demo");
        primaryStage.setScene(new Scene(parent));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

And if a mediator is to be used, things would look like this:

public class Mediator {
    private static Mediator INSTANCE;

    private Stage stage;
    private User user;

    public static Mediator getInstance() {
        if(INSTANCE == null) {
            INSTANCE = new Mediator();
        }
        return INSTANCE;
    }

    private Mediator() {
    }

    public Stage getStage() {
        return stage;
    }

    public void setStage(Stage stage) {
        this.stage = stage;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

public class MainStage extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Mediator.getInstance().setStage(primaryStage);

        Parent parent = FXMLLoader.load(getClass().getResource("scene_1.fxml"));

        primaryStage.setTitle("Demo");
        primaryStage.setScene(new Scene(parent));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

public class ControllerA {
    @FXML
    private TextField usernameTextField;

    @FXML
    private Button loginButton;

    @FXML
    private void initialize() {
        loginButton.setOnAction(event -> {
            try {
                Mediator.getInstance().setUser(new User(usernameTextField.getText()));
                Parent parent = FXMLLoader.load(getClass().getResource("scene_2.fxml"));

                Stage stage = Mediator.getInstance().getStage();
                stage.setScene(new Scene(parent));

            }
            catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}

public class ControllerB {

    @FXML
    private Label wellcomeLabel;

    @FXML
    private void initialize() {
        User user = Mediator.getInstance().getUser();
        wellcomeLabel.setText("Wellcome " + user.getName());
    }

}

FXML files are unrelated to the code that I do not give them.

And class User of course

public class User {
    private String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM