Reputation: 198
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?
Upvotes: 3
Views: 383
Reputation: 198
Since events are propagated upwards according to:
https://docs.oracle.com/javase/8/javafx/events-tutorial/processing.htm
It is necessary to add:
event.consume();
at the end of the handler for the element on the grid so that the right click event does not continue to propagate to the event handler for the GridPane.
Upvotes: 2