hexid
hexid

Reputation: 3811

Make menubar call method when it is clicked?

I am wanting to add an empty javafx.scene.control.Menu to a MenuBar and have it call a method when it is clicked.

I have tried using menu.setOnShowing(new EventHandler<Event>(){}); with no luck.

Here is what I am currently working with:

public MenuBar createMenuBar() {
    MenuBar menuBar = new MenuBar();
    Menu file = new Menu("File");

    Menu addAccountTab = new Menu("Add Tab");
    addAccountTab.setOnShowing(new EventHandler<Event>() {
        public void handle(Event e) {
            System.out.println("addAccountTab Menu clicked.");
        }
    });
    menuBar.getMenus().add(addAccount);
    return menuBar;
}

However, clicking the Menu does not call the onShowing event.

Upvotes: 2

Views: 533

Answers (2)

hexid
hexid

Reputation: 3811

Although the API suggests otherwise, the onShowing event doesn't get called when there are no MenuItems in the Menu or when they are all hidden.

I was able to solve the issue by using Menu's hide() method inside of the onShown event like this.

public MenuBar createMenuBar() {
    MenuBar menuBar = new MenuBar();
    Menu addAccount = MenuBuilder.create()
        .onShown(new EventHandler<Event>() {
            public void handle(Event e) {
                ((Menu)e.getSource()).hide();
                System.out.println("addAccount Clicked");
            }
        }).items(new MenuItem())
        .text("Add Account").build();
    menuBar.getMenus().addAll(addAccount);

    return menuBar;
}

Upvotes: 1

Benjamin Gale
Benjamin Gale

Reputation: 13177

Your Menu needs to contain at least one MenuItem for the event to fire.

public class MenuApplication extends Application {

    @Override
    public void start(Stage primaryStage) {
        MenuBar menuBar = new MenuBar();
        Menu file = new Menu("File");

        Menu addAccountTab = new Menu("Add Tab");

        addAccountTab.setOnShowing(new EventHandler<Event>() {
            @Override
            public void handle(Event e) {
                System.out.println("addAccountTab Menu clicked.");
            }
        });

        MenuItem NewMenuItem = new MenuItem("New");
        addAccountTab.getItems().add(NewMenuItem);

        menuBar.getMenus().addAll(file, addAccountTab);

        StackPane root = new StackPane();
        root.getChildren().add(menuBar);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

The output I get is shown below:

enter image description here

Upvotes: 2

Related Questions