JavaFX 2.0 Activating a Menu like a MenuItem

前端 未结 5 1997
夕颜
夕颜 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:32

    AFAIK, A Menu, if has not any added submenu or Menuitems, does not fire events neither on click, on shown nor on hide. However the workaround is to set its graphic where this graphic node will handle mouse clicks for example,

    Label menuLabel = new Label("File");
    menuLabel.setOnMouseClicked(new EventHandler() {
        @Override
        public void handle(MouseEvent event) {
    
            Stage myDialog = new Stage();
            myDialog.initModality(Modality.WINDOW_MODAL);
    
            Scene myDialogScene = new Scene(VBoxBuilder.create()
                .children(new Text("Hello! it's My Dialog."))
                .alignment(Pos.CENTER)
                .padding(new Insets(10))
                .build());
    
            myDialog.setScene(myDialogScene);
            myDialog.show();
        }
    });
    Menu fileMenuButton = new Menu();
    fileMenuButton.setGraphic(menuLabel);
    menuBar.getMenus().add(fileMenuButton);
    

    A drawback of this approach is that the label do not cover all spaces of the menu resulting clicking on edges of menu is not triggering the mouse event. See this by uncommenting menuLabel.setStyle line above. But this can be resolved by playing with CSS styles I think.
    Code is partially taken from Create Dialog using Stage. You can also load an FXML file into the myDialog stage using the FXMLLoader. There are lots of examples about it on the net.

提交回复
热议问题