Search code examples
javajavafxmenumenuitem

How to grab text from anonymous MenuItem in JavaFX?


My goal is to create MenuItems from an ArrayList, and then add an event to each menuitem that searches the arraylist for the selected menuitem so that it can be transferred over to the next scene. The menu items will be inside a menu button.

    MenuButton selectAccount = new MenuButton("Select an Account");
    selectAccount.setMaxWidth(Double.MAX_VALUE);

    for (int i = 0; i < accountList.size(); i++) {

        //add the items. accountList is my arraylist
        selectAccount.getItems().add(new MenuItem(accountList.get(i).getName()));

        //add the event to items.
        selectAccount.getItems().get(i).setOnAction((ActionEvent e)->{

         // need to grab the text that is inside the menuitem here
         // will run loop to compare text with names in my accountList arraylist
         // if name matches, then the object from arraylist will be loaded into next scene

        });
    }

The trouble I'm having is figuring out how to pull the text from the Menu items. How do I reference the text of these anonymous menu items?


Solution

  • Assuming the type of the elements in accountList is a class Account (just change it accordingly if not), if you use the normal list iteration (instead of an index-based for loop), this all works perfectly naturally:

    MenuButton selectAccount = new MenuButton("Select an Account");
    selectAccount.setMaxWidth(Double.MAX_VALUE);
    
    for (Account account : accountList) {
    
        MenuItem item = new MenuItem(account.getName());
        selectAccount.getItems().add(item);
    
        item.setOnAction((ActionEvent e)->{
    
            // now just do whatever you need to do with account, e.g.
            showAccountDetails(account);
    
        });
    }