如何在javafx中从匿名菜单项中获取文本?

1bqhqjot  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(366)

我的目标是从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

        });
    }

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

osh3o9ms

osh3o9ms1#

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

    });
}

相关问题