How to set the root Stage of a controller?

Asked

Viewed 151 times

2

I created a login screen that when authenticating redirects to the menu, but calling 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");
    }
}

I’ve tried instantiating Main in the controller to access primaryStage and nothing, how could I perform this screen swap? alias I started messing today with javafx this would be the most practical way?

1 answer

1


I managed to solve, 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 in the Logincontroller calling in:

@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.");
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.