簡體   English   中英

如何在ActionListener的actionPerformed內部傳遞循環索引

[英]How to pass for loop index inside ActionListener's actionPerformed [Java]

我想知道是否有一種使用循環分配點擊事件的方法。 我正在尋找的快速示例:每個按鈕將在myMethod(int)內執行操作的位置。

因此, button[2]應該執行myMethod(2)等等。

// imports...    
public class MyClass {

        private JButton[] buttons = new JButton[10];

        public MyClass() {
            // constructor

            for ( int i = 0; i < this.buttons.length; i++ ) {
             this.buttons[i].addActionListener( new ActionListener() {
                    public void actionPerformed( ActionEvent e ) {                  
                        MyClass.this.myMethod(i);
                    }
                });
            }
        }

        public void myMethod( int id ) {
            // perform actions
            //...
        }



    }

上面的代碼引發錯誤,該變量必須是final或有效的final。 我知道為什么,但是我該怎么做呢?

只需創建臨時最終變量並為其分配i值即可。 現在,您可以使用最終變量將其傳遞給myMethod ,如下所示:

// imports...    
public class MyClass {

    private JButton[] buttons = new JButton[10];

    public MyClass() {
        // constructor

        for (int i = 0; i < this.buttons.length; i++) {
            final int myFinalIndex = i;
            this.buttons[i].addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    MyClass.this.myMethod(myFinalIndex);
                }
            });
        }
    }

    public void myMethod(int id) {
        // perform actions
        // ...
    }

}

暫無
暫無

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

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