How to add context menu to an image in JavaFX?

A context menu is a popup menu that appears on interacting with the UI elements in the application. You can create a context menu by instantiating the javafx.scene.control.ContextMenu class. Just like a menu, after creating a context menu, you need to add MenuItems to it.

Typically, a context menu appears when you “right-click” on the attached control.

Setting ContextMenu to nodes −

You can set ContextMenu to any object of the javafx.scene.control class, using the setContextMenu() method.

Every node has a property named onContextMenuRequested, this defines a function to be called when a context menu has been requested on this Node. You can set value to this property using the setOnContextMenuRequested() menu.

To set a context menu to an image view, create an ImageView object embedding the desired image, invoke the setOnContextMenuRequested() method on it.


import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ContextMenuImage extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating the image view
      ImageView imageView = new ImageView();
      //Setting the image view parameters
      // imageView.setFitHeight(295);
      InputStream stream = new FileInputStream("D:\images\elephant.jpg");
      Image image = new Image(stream);
      //Creating a context menu
      ContextMenu contextMenu = new ContextMenu();
      //Creating the menu Items for the context menu
      MenuItem item1 = new MenuItem("Copy");
      MenuItem item2 = new MenuItem("remove");
      contextMenu.getItems().addAll(item1, item2);
      //Setting action to the context menu item
      item1.setOnAction((ActionEvent e) -> {
         Clipboard clipboard = Clipboard.getSystemClipboard();
         ClipboardContent content = new ClipboardContent();
      //Setting action to the context menu item
      item2.setOnAction((ActionEvent e) -> {
      //Setting context menu to the image view
      imageView.setOnContextMenuRequested(new EventHandler() {
         public void handle(ContextMenuEvent event) {
  , event.getScreenX(), event.getScreenY());
      HBox box = new HBox();
      box.setPadding(new Insets(10, 10, 10, 10));
      //Setting the stage
      Group root = new Group(box);
      Scene scene = new Scene(root, 595, 360, Color.BEIGE);
   public static void main(String args[]){