如何从 JavaFX 中的匿名 MenuItem 中获取文本?
How to grab text from anonymous MenuItem in JavaFX?
我的目标是从 ArrayList 创建 MenuItems,然后向每个菜单项添加一个事件,该事件在 arraylist 中搜索所选菜单项,以便它可以转移到下一个场景。菜单项将位于菜单按钮内。
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
中元素的类型是 class Account
(如果不是,则相应地更改它),如果您使用普通列表迭代(而不是 index-based for loop),这一切都自然而然地工作:
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);
});
}
我的目标是从 ArrayList 创建 MenuItems,然后向每个菜单项添加一个事件,该事件在 arraylist 中搜索所选菜单项,以便它可以转移到下一个场景。菜单项将位于菜单按钮内。
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
中元素的类型是 class Account
(如果不是,则相应地更改它),如果您使用普通列表迭代(而不是 index-based for loop),这一切都自然而然地工作:
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);
});
}