2

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

baka1408
  • 433
  • 4
  • 21

3 Answers3

4
Canvas canvas = ... ;
ContextMenu menu = ... ;

canvas.setOnContextMenuRequested(e -> menu.show(canvas, e.getScreenX(), e.getScreenY()));
James_D
  • 201,275
  • 16
  • 291
  • 322
0

James_D's solution may not dismiss the menu when clicking the canvas while the context menu is visible. See this bug :

https://bugs.openjdk.java.net/browse/JDK-8095591

So instead, I suggest using :

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

canvas.setOnContextMenuRequested(e -> menu.show(canvas.getScene().getWindow(), e.getScreenX(), e.getScreenY()));
nickthecoder
  • 121
  • 1
  • 3
-1

Maybe you can use Chrome extension's contextMenu. here is the official document.

The only issue so far I find is that the Context type for a canvas is not clear. ["all"] works but is not a good way.

Zephyr
  • 6,123
  • 34
  • 33