提问者:小点点

JavaFx控制器设置对象另一个控制器


我在LoginController中获取Admin对象。它不为空没有问题。当我设置这个对象时,AdminController不起作用。在我的初始化系统结果中显示“null”。我需要在我的另一个控制器中使用这个对象。使用摇摆我在控制器构造函数和摇摆构造器中做到了这一点。但是我不知道如何使用JavaFx做到这一点。对不起,我的英语不好。但是如果你看代码,你会理解我的。

    public class UserLoginController extends AbstractController {

    @FXML
    private Button joinBtn;
    @FXML
    private Button exitBtn;
    @FXML
    private Label statusLabel;
    @FXML
    private TextField userNo;
    @FXML
    private PasswordField password;


    @FXML
    void buttonEvent(ActionEvent event) {

        if (joinBtn == event.getSource()) {
            String userType = userNo.getText().substring(0, 2);
            switch (userType) {
            case "10":
                Admin admin = DBContext.getInstance().admins().isUserExist(Integer.parseInt(userNo.getText()), password.getText());
                if(admin != null) {
                    final String fxml = "/educationManagement/view/AdminPanel.fxml";
                    try {
                        FXMLLoader loader = new FXMLLoader(getClass().getResource(fxml));
                        Parent root = (Parent) loader.load();
                        AdminController adminController = loader.getController();
                        adminController.setAdmin(admin);
                        Scene scene = new Scene(root);
                        Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
                        stage.setTitle(admin.getFirstName() + " " + admin.getLastName());
                        stage.setScene(scene);
                        stage.show();
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("fuck");
                    }

                } else {
                    statusLabel.setText("Kullanıcı Adı veya Şifre Yanlış");
                    userNo.setText("");
                    password.setText("");
                }
                break;

            case "40":

                break;

            case "50":

                break;

            default:
                statusLabel.setText("Kullanıcı Adı Bulunamadı");
                break;
            }

        }
    }
}


public class AdminController implements Initializable{

    private Admin admin;

    @FXML
    private TableView<Student> studentTable;

    @FXML
    private Label firstNameLbl;

    public Admin getAdmin() {
        return admin;
    }

    public void setAdmin(Admin admin) {
        this.admin = admin;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        System.out.println(admin);

    }

}

共1个答案

匿名用户

加载FXML文件时正在调用初始化方法,您应该在AdminController中创建另一个初始化方法,该方法将使用admin对象完成您需要的所有初始化,并在调用setter后调用此方法:

 AdminController adminController = loader.getController();
 adminController.setAdmin(admin);
 adminController.initController();