JavaFX 2.0 Activating a Menu like a MenuItem

前端 未结 5 2031
夕颜
夕颜 2020-12-01 12:51

I\'m making a MenuBar, and I wan\'t the functionality to press a Menu like: \"File\" and then execute a action. Such like opening an other fxml, or

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 13:43

    Combining with the answer from our friend @Dota2, i built a helper class to trigger the Menu's onAction(Menu menu) event even if it does not have any MenuItem inside. Here is the static helper method:

    public static void onAction(Menu menu)
    {
        final MenuItem menuItem = new MenuItem();
    
        menu.getItems().add(menuItem);
        menu.addEventHandler(Menu.ON_SHOWN, event -> menu.hide());
        menu.addEventHandler(Menu.ON_SHOWING, event -> menu.fire());
    }
    

    Then you call:

    YourHelperClass.onAction(myMenu);
    

    And ready! I hope this helps.

提交回复
热议问题