繁体   English   中英

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

[英]How to grab text from anonymous MenuItem in JavaFX?

我的目标是从 ArrayList 创建 MenuItems,然后向每个 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 中元素的类型是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);

    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM