How do i show a context menu when right click on a

2019-04-02 10:20发布

问题:

I am trying to show a context menu i created, when i right click on a pane or an image view ((on Context Menu Requested)). The problem is they don't seem to have a setContextMenue method, unlike labels and buttons...etc. How can associate a context menu to a node that doesn't seem to accept context menus?

@FXML
Button button1, button2;

@FXML
Pane mainPane;

@FXML
ImageView image;
private void initContextMenu() {
    final ContextMenu contextMenu = new ContextMenu();
    final MenuItem item1 = new MenuItem("open a file");
    final MenuItem item2 = new MenuItem("quit");

    contextMenu.getItems().addAll(item1, item2);

    // not possible
    image.setContextMenu(contextMenu);
    // possible
    button1.setContextMenu(contextMenu)

回答1:

You can do

image.setOnContextMenuRequested(e -> 
    contextMenu.show(image, e.getScreenX(), e.getScreenY()));