簡體   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