How to set the root stage of a controller?

2

I created a login screen that when authenticating redirects to the menu, but making the call by the controller does not work.

Main:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {
        Parent root = FXMLLoader.load(getClass().getResource("view/Login.fxml"));
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}

LoginController:

@FXML
void logar(ActionEvent event) throws IOException {
    if (LoginDao.autenticar(text_usuario.getText(), text_senha.getText())) {
        Parent blah = FXMLLoader.load(getClass().getResource("view/Menu.fxml"));
        Scene scene = new Scene(blah);
        Stage appStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        appStage.setScene(scene);
        appStage.show();
    } else {
        System.out.println("login ou senha incorretos");
    }
}

Have I tried to instantiate Main in the controller to access primaryStage and nothing, how could I perform this screen switching? alias I started to move today with javaFX would this be the most practical?

    
asked by anonymous 11.05.2016 / 03:41

1 answer

1

I was able to solve it, I implemented the following method in my main:

public void setView(String title, String url) throws IOException {
    FXMLLoader loader = new FXMLLoader(CobPlus.class.getResource(url + ".fxml"));
    AnchorPane view = (AnchorPane) loader.load();
    Scene scene = new Scene(view);
    Stage stage = new Stage();
    stage.getIcons().add(new Image(getClass().getResourceAsStream("icon.png")));
    stage.setTitle(title);
    stage.setScene(scene);
    stage.show();
}

public void closeView(Event event){
    ((Node)(event.getSource())).getScene().getWindow().hide();
}

And at LoginController I called:

@FXML
void logar(ActionEvent event) throws IOException {
    if(LoginDao.autenticar(text_usuario.getText(), text_senha.getText())){
    cob.plus.CobPlus cob = new cob.plus.CobPlus();
    cob.closeView(event);
    cob.setView("Menu", "view/MenuView");
    }else{
        System.out.println("Usuario ou senha incorretos.");
    }
}
    
12.05.2016 / 04:49