I am trying to change the scene in a javafx stage based on menuItem click. Here is my sample.fxml:
Here is a way to get the Scene and Window based on a menu item being clicked without it being an injected FXML element, or without referencing it if you did create it with FXML. In other words by using the Event's target.
In my problem I had a MenuButton with a dropdown menu (a ContextMenu as I found out, which I didn't know as I had created my menu in FXML) containing MenuItems and I wanted to open a FileChooser, which needs the Window as an argument, when the "Save" MenuItem was clicked.
Normally I would have gone down the route of getting the event's target, then the Parent, then the next Parent etc. and finally the Scene and then Window. As Menu and MenuItem are not Nodes and therefore do not have Parents In this case however I did the following:
FileChooser fileChooser = new FileChooser();
MenuItem menuItem = (MenuItem)event.getTarget();
ContextMenu cm = menuItem.getParentPopup();
Scene scene = cm.getScene();
Window window = scene.getWindow();
fileChooser.showSaveDialog(window);
Or, converting the bulk into a one line argument:
FileChooser fileChooser = new FileChooser();
fileChooser.showSaveDialog(((MenuItem)event.getTarget()).getParentPopup().getScene().getWindow());
Just adapt this as necessary based on your own scene-graph (i.e. how many parents you need to get through in cases of sub-menus etc) and what you are wanting to do once you have the Window, but once you get to the ContextMenu (the popup list of MenuItems), you can get the Scene and then from that get the Window.
As an aside, here is the FXML I used to create my MenuButton, and hence why I didn't realise I had to get the ContextMenu through a call to getParentPopup() without some trial and error: