JavaFX allows primary stages to swap out scenes. However, JavaFX stages don’t handle MenuBars directly. So what if you want to swap JavaFX scenes, but need to share one MenuBar between them? The trick is using a BorderPane as a root pane of your scene to hold a top JavaFx MenuBar and a central pane that gets swapped, instead of swapping the primary stage’s scene.
This example creates a Main class, a menu controller class, and three FXML files. The FXML files are a MenuBar, and two AnchorPanes that we swap between. All the custom code is included below for quick reference.
JavaFX menu creation is essential to most complex applications. This JavaFx tutorial explains how to create menus using FXML. If need a quick introduction to JavaFX, check out my beginner’s tutorial, JavaFX 8 Hello World for Eclipse.
In case you’re new to JavaFX, or been away for a while, JavaFX 8 applications are arranged with a Stage, a Scene, Groups, and Leaf Nodes. The Stage is the application’s window. The Scene has the containers such as AnchorPanes and BorderPanes. Containers hold other containers, and leaf nodes. Leaf nodes are Controls such as Buttons, Labels, and text files.