简体   繁体   English

如何在ActionListener的actionPerformed内部传递循环索引

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

I was wondering if there is a way to assign click event using a loop. 我想知道是否有一种使用循环分配点击事件的方法。 Quick example of what I looking for: Where each button will do actions inside myMethod(int) . 我正在寻找的快速示例:每个按钮将在myMethod(int)内执行操作的位置。

So button[2] should do myMethod(2) and so on. 因此, 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
            //...
        }



    }

The code above throws error that the variable must be final or effecively final. 上面的代码引发错误,该变量必须是final或有效的final。 I know why, but how can I do similiar thing? 我知道为什么,但是我该怎么做呢?

Just create temporary final variable and assign i value to it. 只需创建临时最终变量并为其分配i值即可。 Now you can use the final variable to pass it to myMethod , like below: 现在,您可以使用最终变量将其传递给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