Search code examples
javafxjavafx-11

JavaFX MenuItem, handling the event


I'm developing an small application and I have a problem when creating the menu bar. This is my start method:

public void start(@SuppressWarnings("exports") Stage prymaryStage) throws Exception {
        // Stats menu
        Menu statsMenu = new Menu("Stats");

        // PairName menu
        Menu pairNameMenu = new Menu("Choose pair");

        // Stats Menu items
        MenuItem gStats = new MenuItem("General stats");

        // Pair list
        ArrayList<String> pairNameList = DatabaseMethods.returnPairNameList();

        // PairName items (probably i will have to change)
        for (String item : pairNameList) {
            pairNameMenu.getItems().add(new MenuItem(item));
        }

        statsMenu.getItems().addAll(gStats, pairNameMenu);

        // Main menu bar
        MenuBar menuBar = new MenuBar();
        menuBar.getMenus().addAll(statsMenu);

        // BorderPane settings
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(menuBar);

        Scene scene = new Scene(borderPane, 1200, 800);

        prymaryStage.setTitle("English minimal pair training");
        prymaryStage.setScene(scene);
        prymaryStage.show();

    }

The problem I have is in this part of the code:

        ArrayList<String> pairNameList = DatabaseMethods.returnPairNameList();

        // PairName items (probably i will have to change)
        for (String item : pairNameList) {
            pairNameMenu.getItems().add(new MenuItem(item));
        }

I was trying to create the items of a submenu from an ArrayList. This data is fetch from a database and the data is returned in form of an ArrayList. I didn't find any other way to do the menu items than pairNameMenu.getItems().add(new MenuItem(item)); inside the for loop.

Now I want to handle the click in the items but I don't know how to do it. I've tried with .setOnAction but Eclipse says the .add(new MenuItem(item)) can't be use in that case and recomends .addAll and the same happens, Eclipse says that's an error and recomends .add I tried to add this code after new MenuItem(item)

.addEventHandler(new EventHandler<ActionEvent>() {
 public void handle(ActionEvent even) {
}
})

But it didn't work either.

I'm pretty new to Java and JavaFX, this is my first project so sorry if this is a very basic question.

Thank you for your time


Solution

  • You have to loop through pairNameMenu items after you have created and added all the items to pairNameMenu:

    pairNameMenu.getItems().foreach((item) ->{
        item.addEventHandler.....
        ....
        ....
    });
    

    or do something like below when creating the MenuItems:

    for (String item : pairNameList) {
        MenuItem tempMenuItem = new MenuItem(item);
        tempMenuItem..addEventHandler.....
        ....
        ....
        pairNameMenu.getItems().add(tempMenuItem);
    }