我想知道是否有一种方法可以使用循环分配点击事件。
我正在寻找的简单示例:
每个按钮都会在 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
//...
}
}
上面的代码会抛出错误,表明该变量必须是最终的或有效的最终变量。我知道为什么,但我怎样才能做类似的事情呢?
最佳答案
只需创建临时最终变量并为其分配 i
值即可。现在您可以使用 Final 变量将其传递给 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
// ...
}
}
关于java - 如何在 ActionListener 的 actionPerformed 中传递 for 循环索引 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220857/