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)
.
So button[2]
should do myMethod(2)
and so on.
// 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. I know why, but how can I do similiar thing?
Just create temporary final variable and assign i
value to it. Now you can use the final variable to pass it to myMethod
, like below:
// 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
// ...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.