簡體   English   中英

如何從另一個actionListener內部的actionListener訪問變量?

[英]How can I access a variable from an actionListener insider another actionListener?

private int var = 0;

test(){
    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String selection = (String) items.getSelectedItem();

            for (int i = 0; i < itms.length; i++) {
                if (selection == itms[i]) {
                    var = 10 + i;

                    System.out.println(var); // prints the desired value
                }
            }
        }
    };

    System.out.println(var); // prints 0 but why not desired value???
}

此actionListener用於組合框。 我想在組合框中獲取所選項目的值,並將其提供給另一個actionListener,后者將根據選擇的JButton將新的值附加到原始actionListener的var中。 如何從此actionListener內部獲取var的值,並在也位於同一構造函數中的另一個actionListener中使用它? 那有可能嗎? 有沒有更好的方法?

您的actionPerformed()方法將在事件發生時執行,但是在actionPerformed()之外的print語句則不是這種情況。

所以這句話

System.out.println(var); // prints 0 but why not desired value???

每當您創建test類的對象(根據Java命名約定將其命名為Test類)時,都會被執行,因為print語句是在構造函數內部編寫的。 相反,每當事件發生時, actionPerformed方法中的print語句將被執行並打印正確的值,即您的“期望值”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM