英文:
How to grab text from anonymous MenuItem in JavaFX?
问题
我的目标是从一个ArrayList创建MenuItems,然后为每个menuitem添加一个事件,该事件搜索所选menuitem的ArrayList,以便将其传送到下一个场景。这些菜单项将位于一个菜单按钮内。
MenuButton selectAccount = new MenuButton("选择一个帐户");
selectAccount.setMaxWidth(Double.MAX_VALUE);
for (int i = 0; i < accountList.size(); i++) {
// 添加菜单项。accountList是我的ArrayList
selectAccount.getItems().add(new MenuItem(accountList.get(i).getName()));
// 为菜单项添加事件。
selectAccount.getItems().get(i).setOnAction((ActionEvent e) -> {
// 在这里获取菜单项内的文本
// 将运行循环以将文本与我的accountList ArrayList中的名称进行比较
// 如果名称匹配,则将来自ArrayList的对象加载到下一个场景中
});
}
我遇到的问题是如何提取菜单项的文本。我如何引用这些匿名菜单项的文本?
英文:
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?
答案1
得分: 0
假设accountList
中元素的类型是Account
类(如果不是,请相应地进行更改),如果您使用普通的列表迭代(而不是基于索引的for循环),所有这些都可以正常工作:
MenuButton selectAccount = new MenuButton("选择一个账户");
selectAccount.setMaxWidth(Double.MAX_VALUE);
for (Account account : accountList) {
MenuItem item = new MenuItem(account.getName());
selectAccount.getItems().add(item);
item.setOnAction((ActionEvent e) -> {
// 现在,您可以根据需要处理账户,例如
showAccountDetails(account);
});
}
英文:
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);
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论