baka1408 baka1408 - 7 months ago 48
Java Question

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.).

Answer
Canvas canvas = ... ;
ContextMenu menu = ... ;

canvas.setOnContextMenuRequested(e -> menu.show(canvas, e.getScreenX(), e.getScreenY()));