0

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;
}
7
  • Please provide a minimal reproducible example that demonstrates the problem.
    – kleopatra
    Dec 15, 2018 at 16:30
  • @kleopatra What do you feel could be added to enhance the question? I could provide an example of code that can be run without modification, but it would be several hundred lines of code. Dec 15, 2018 at 16:34
  • several hundred lines is not "minimal" ;) Nobody wants to wade through tons of unrelated code, strip the essence down to 50 or so - that's always enough to demonstrate the gist of what you are after and why the outcome is not what you expect.
    – kleopatra
    Dec 15, 2018 at 16:39
  • 1
    after writing such an example you'll be more experienced :)
    – kleopatra
    Dec 15, 2018 at 16:41
  • 1
    @kleopatra I have reduced down my examples while still making the methods themselves runnable, albeit as long as they have other code surrounding them. I have also modified to include my version of the code Slaw suggested. Please let me know if there is anything else I can do to improve the question. Dec 15, 2018 at 17:17

1 Answer 1

2

Here's a small example (some explanations are in code-comments):

import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.Window;

public class Main extends Application {

  private ContextMenu menu;

  @Override
  public void start(Stage primaryStage) {
    primaryStage.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
      if (event.getCode() == KeyCode.ESCAPE) {
        event.consume();
        showContextMenu(primaryStage);
      }
    });

    Label label = new Label("Press ESC to show ContextMenu.");
    primaryStage.setScene(new Scene(new StackPane(label), 500, 300));
    primaryStage.show();
  }

  private void showContextMenu(Window owner) {
    if (menu == null) {
      menu = new ContextMenu(
          new MenuItem("Copy"),
          new MenuItem("Cut"),
          new MenuItem("Paste"),
          new SeparatorMenuItem(),
          new MenuItem("Delete")
      );

      /*
       * Adjusts the ContextMenu's position once shown so that the center
       * of the ContextMenu is at the center of the screen (rather than
       * the top left corner). Do this here because the ContextMenu needs
       * to have been displayed in order to know the dimensions.
       *
       * Since the top left corner is already centered on the screen we don't need
       * to know the dimensions of the screen. We only need to move the ContextMenu
       * relative to itself.
       */
      menu.setOnShown(event -> {
        event.consume();
        menu.setAnchorX(menu.getAnchorX() - menu.getWidth() / 2.0);
        menu.setAnchorY(menu.getAnchorY() - menu.getHeight() / 2.0);
      });
    }

    /*
     * Displays the ContextMenu on the primary screen. The top left corner
     * of the ContextMenu will be at the center of the screen. Will need
     * to adjust the ContextMenu's position after it's shown.
     */
    Rectangle2D bounds = Screen.getPrimary().getVisualBounds();
    menu.show(owner, bounds.getWidth() / 2.0, bounds.getHeight() / 2.0);
  }

}
5
  • Thank you for the detailed example. Unfortunately, this doesn't seem to work for me. I think it might be because I'm calling it from outside the Main class. I will make a mention of that in my question. Do you think there is something else I could try? Dec 15, 2018 at 16:26
  • @LuminousNutria From where you're calling this code shouldn't matter, as far as I know.
    – Slaw
    Dec 15, 2018 at 16:34
  • I don't mind doing that, but could you provide more information on what you would like to see? I cannot provide an example that can be run by itself without several hundred more lines of code. Dec 15, 2018 at 16:36
  • 2
    @LuminousNutria A minimal reproducible example should be specifically and specially created for Stack Overflow. It should basically be a (runnable) mock of whatever you're trying to do. Much of your current code is likely not relevant to the problem at hand. If in your quest to create a MCVE the problem goes away you may even be able to find the problem yourself.
    – Slaw
    Dec 15, 2018 at 16:38
  • That's kind of the issue I'm confused about. I don't know how to create a runnable example in JavaFX without lots of code that's irrelevant to the problem at hand. I am not always sure what is relevant. Dec 15, 2018 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.