JavaFX 2.0 Activating a Menu like a MenuItem

前端 未结 5 2043
夕颜
夕颜 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

    Recently I faced the same issue, this was my way out:

    I had a menuItem in the menu, which was to behave as if the menuItem is clicked (in your case File menu). So what you can do is have a menuItem Dummy_menuItem

    final Menu fileMenu = new Menu("File");
    fileMenu.getItems().add(new MenuItem("Dummy_menuItem"));
    menuBar.getMenus().add(fileMenu);
    

    and then on click of File menu, fire the Dummy_menuItem menuItem or any functionality you wish to have. To identify which menu should have this property, I used numberOfMenuItems to get the number of menuItems in the menus in menubar

    if (numberOfMenuItems == 1) {
        menu.showingProperty().addListener(
            (observableValue, oldValue, newValue) -> {
                if (newValue) {
                    // the first menuItem is triggered
                    menu.getItems().get(0).fire();
                }
            }
        );
    }
    

    the outcome is that the Dummy_menuItem is triggered without the context displaying the menuItem on click of File menu or any menu that has one menuItem. So it appears as if you clicked the File menu and were redirected to another page or whatever.

    Hope this helps!!

提交回复
热议问题