Search code examples
javajavafxfxmlscenebuilderscene

FXML to open a new scene via button


I am using Scene Builder to create a JavaFX GUI application. I am trying to implement something like this, using FXML:

reportButton = new Button("Report");
reportButton.setOnAction(e -> ReportPage.display());

but I can't figure it out how to do that using the controller page. Can someone please tell me how do I do that? Thank you


Solution

  • Here is how could show a new stage. Add this code in your on action function
    (you can add that function with scene builder in code : On action property)

    @FXML
    private void reportButtonHandler(ActionEvent event) {
        FXMLLoader fxmlLoader = new 
            FXMLLoader(getClass().getResource("pathtofxml/ReportPage.fxml"));
        Parent root1 = (Parent) fxmlLoader.load();
        Stage stage = new Stage();
        //set what you want on your stage
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.setTitle("Report Page");
        stage.setScene(new Scene(root1));
        stage.setResizable(false);
        stage.show();
    }