JavaFX ContextMenu add to the entire scene graph

Introduction

To Add the context menu to the entire scene graph in JavaFX

// Add the context menu to the entire scene graph.
rootNode.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
  public void handle(ContextMenuEvent ae) {
    // Popup menu at the location of the right click.
    editMenu.show(rootNode, ae.getScreenX(), ae.getScreenY());
  }
});

Full source


import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Main extends Application {
  //Create a label that will report the selection.
  private Label response = new Label("Menu Demo");

  public static void main(String[] args) {
    launch(args);//  ww w  .j  a v  a 2  s  .  co m
  }
  public void start(Stage myStage) {    myStage.setTitle("Menus from java2s.com");

    // Use a BorderPane for the root node.
    BorderPane rootNode = new BorderPane();

    Scene myScene = new Scene(rootNode, 300, 300);

    myStage.setScene(myScene);

    // Create the edit context menu items.
    MenuItem cut = new MenuItem("Cut");
    MenuItem copy = new MenuItem("Copy");
    MenuItem paste = new MenuItem("Paste");

    // Create a context (i.e., pop up) menu that shows edit options.
    ContextMenu editMenu = new ContextMenu(cut, copy, paste);

    // Set the action event handlers.
    cut.setOnAction(e->{
      String name = ((MenuItem) e.getTarget()).getText();
      response.setText(name + " selected");
  
    });
    copy.setOnAction(e->{
      String name = ((MenuItem) e.getTarget()).getText();
      response.setText(name + " selected");
  
    });
    paste.setOnAction(e->{
      String name = ((MenuItem) e.getTarget()).getText();
      response.setText(name + " selected");
    });
    rootNode.setCenter(response);

    // Add the context menu to the entire scene graph.
    rootNode.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
      public void handle(ContextMenuEvent ae) {
        // Popup menu at the location of the right click.
        editMenu.show(rootNode, ae.getScreenX(), ae.getScreenY());
      }
    });
    
    myStage.show();
  }
}



PreviousNext

Related