如何从JavaFX中的匿名MenuItem抓取文本?

问题描述

我的目标是从ArrayList创建MenuItem,然后向每个menuitem添加一个事件,该事件在arraylist中搜索选定的menuitem,以便可以将其转移到下一个场景。菜单项将在菜单按钮内。

    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

        });
    }

我遇到的麻烦是弄清楚如何从菜单项中提取文本。如何引用这些匿名菜单项的文本?

解决方法

假设accountList中元素的类型是类Account(如果没有,则相应地进行更改),如果您使用常规列表迭代(而不是基于索引的for循环),这一切自然完美地完成了:

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);

    });
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...