javajavafxcontextmenujava-canvas

How to add context menu to a canvas element?


Problem : It is not possible to simply 'add' ContextMenu to a Canvas or Pane element via addContextMenu(menu), which works only with javafx.scene.control elements (and neither Canvas or Panel extends this class).

Question : Is there any 'clean' way to 'register' ContextMenu item to a Canvas element? I expect standard behavior of this menu (to show after RMB clicked on Canvas element, autohide when clicked with LMB etc.).


Solution

  • Canvas canvas = ... ;
    ContextMenu menu = ... ;
    
    canvas.setOnContextMenuRequested(e -> menu.show(canvas, e.getScreenX(), e.getScreenY()));