3

I want to develop a multiple scenes Java FX application. But I want to have the common menu across all scenes. I think using FXML I can create a menu in a scene. But Can I have the same menu across all the scenes even after I navigated to other screen?

If so how is it. Else let me know any alternative for it.

gibsosmart
  • 137
  • 1
  • 8

1 Answers1

3

Yes this is possible. I'm using this mechanism in my own application.

What I do first is make an FXML with the menu bar and an AnchorPane who contains the content. This FXML is loaded when the application starts.

I use a Context class (based on the answer of Sergey in this question: Multiple FXML with Controllers, share object) which contains a method ShowContentPane(String url) method:

public void showContentPane(String sURL){
    try {
        getContentPane().getChildren().clear();
        URL url = getClass().getResource(sURL);

        //this method returns the AnchorPane pContent
        AnchorPane n = (AnchorPane) FXMLLoader.load(url, ResourceBundle.getBundle("src.bundles.bundle", getLocale()));
        AnchorPane.setTopAnchor(n, 0.0);
        AnchorPane.setBottomAnchor(n, 0.0);
        AnchorPane.setLeftAnchor(n, 0.0);
        AnchorPane.setRightAnchor(n, 0.0);

        getContentPane().getChildren().add(n);

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

So what basically happens is:

When the program starts, set content pane in the Context:

@Override
public void initialize(URL url, ResourceBundle rb) {
    Context.getInstance().setContentPane(pContent); //pContent is the name of the AnchorPane containing the content
    ...
}

When a button or menuitem is chosen, I load the FXML in the content Pane:

@FXML
private void handle_FarmerListButton(ActionEvent event) {
    Context.getInstance().showContentPane("/GUI/user/ListUser.fxml");
}

Hope this helps :)

Gravity Grave
  • 2,802
  • 1
  • 27
  • 39
Perneel
  • 3,317
  • 7
  • 45
  • 66