I am using a JavaFX ContextMenu with a GridPane, on the GridPane I also am placing Rectangles that have ContextMenus of their own. Both context menus fire on a click of the right mouse button.
The event handler on the GridPane looks like this:
this.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
if (event.getButton().equals(MouseButton.SECONDARY)) {
ContextMenu cm = new ContextMenu();
MenuItem newElement = new MenuItem("Add Element");
addElement.setOnAction(menuEvent -> { /* Logic for handling context menu action */ });
cm.getItems.add(newElement);
cm.show(this,event.getScreenX(),event.getScreenY());
}
});
The event handler on the Rectangle
on the grid looks like this:
this.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
// Right click
if (event.getButton().equals(MouseButton.SECONDARY)) {
this.requestFocus();
ContextMenu cm = new ContextMenu();
MenuItem toRemove = new MenuItem("Delete Element");
toRemove .setOnAction(menuEvent -> {
/* Logic for removing element */
});
cm.getItems().add(toRemove );
cm.show(this, event.getScreenX(), event.getScreenY());
}
});
How do I ensure that only the context menu for the element that is on the GridPane is shown if the right click is on that element?