I am trying to create a ContextMenu that appears in the middle of the screen whenever the keyboard's escape button is pressed. I want to use it to handle loading, saving, and exiting in my game. It will be called from classes outside of Main.
The problem is I'm not sure how to find out the ContextMenu's height and width in pixels. so, I'm at a loss as far as how to center it in a window. I am trying to use Rectangle2D to find the center, but it is still slightly off.
How can I display my ContextMenu in the middle of the screen?
Displays my ContextMenu:
/**
* Returns the Pane object so it can be made into a Scene object.
* Each Scene has it's own class
* Each class uses this method to create a Pane object for it.
* @return Pane
*/
public Pane getPane() {
// create a GridPane object
grid = new GridPane();
// create ContextMenu and set anchor points.
ContextMenu cm = Main.Org.createPopUpMenu();
cm.setOnShowing(event -> {
event.consume();
cm.setAnchorX(cm.getAnchorX() - cm.getWidth() / 2.0);
cm.setAnchorY(cm.getAnchorY() - cm.getHeight() / 2.0);
});
Rectangle2D bounds = Screen.getPrimary().getVisualBounds();
// show ContextMenu if escape key is pressed.
grid.setOnKeyReleased( event -> {
if(event.getCode() == KeyCode.ESCAPE) {
cm.show(grid, bounds.getWidth() / 2.0, bounds.getHeight() / 2.0);
}
});
return grid;
}
Organizer class createPopUpMenu()
method:
/**
* Creates a pop-up menu for saving, loading, and exiting the game
* @return ContextMenu
*/
public ContextMenu createPopUpMenu() {
ContextMenu contextMenu = new ContextMenu();
MenuItem menuItem = new MenuItem();
//create ImageViews
image = new ImageView("/images/PopUpMenu_Exit.png");
// add ImageViews to MenuItems
menuItem.setGraphic(image);
contextMenu.getItems().add(menuItem);
menuItem.setOnAction( a -> {
// quit the game
Platform.exit();
System.exit(0);
});
return contextMenu;
}