javafxjava-8javafx-2javafx-8

Adding mouse event handler to menu in javafx


I am new to javafx and is currently working on menu, menuitems. I wish to override the default event of displaying contextMenu, which is currently shown even if menu is not pressed but mouse is hovered over it while neighbouring menu's contextMenu is shown. This happens in every application, since its very handy. But for some reason I do not need it. I tried capturing the mouse event on menu,so that I can work accordingly, but nothing happens.

menu.addEventHandler(MouseEvent.ANY, event -> {
            System.out.println("Mouse event occured");
            });

here menu is the one to which I want to add this behaviour.


Solution

  • It is true that one cannot add mouse-event to menu in javafx directly, but there's a workaround that I managed to figure out. Now the workaround involves menuBar (on which menu is placed), which can capture the mouse-event. So adding a eventFilter on menuBar for mouse-event,

        // variable to store the mouse-event-type 
           private MouseEvent mouseEventType
    
        // for registering mouse pressed event;
        // addEventFilter since it is called during the capturing phase
          mainMenu.addEventFilter(MouseEvent.ANY, mouseEvent -> {
          mouseEventType = mouseEvent;
        });
    

    and then handling the event in menu.setOnShown does the trick.

       // handle the mouse-event like this
          menu.setOnShown( event -> {
                 if(mouseEventType.getEventType().equals(MouseEvent.MOUSE_PRESSED)){
                     //TODO something
                 }else{
                     //TODO something 
                 }
                });
    

    So what happens here is that, mouseEventType is initialized to MouseEvent.MOUSE_PRESSED on click on the menu, and instantly the setOnShown is invoked with default action of showing contextMenu containing the menuItems. Now accordingly different logic can be given.