Add actionPerformed with array

The ‘Anonymous’ new ActionListener() {...} (it can be replaced with a lambda) you are trying to create is something it will be executed after the action on the button will be done. To be able to compile the values used inside that anonymous/lambda they need to be final to guarantee they are accessible on runtime.

A quick fix can be something like:

final int finalI = i;
final int finalK = k;
buttonfields[i][k].addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("You clicked the Button" + finalI + ", " + finalK);
        System.out.println("Does that work:" + buttonfields[finalI][finalK]);
    }
});

In addition, using lambdas the code can look like:

final int finalI = i;
final int finalK = k;
buttonfields[i][k].addActionListener(e -> {
    System.out.println("You clicked the Button" + finalI + ", " + finalK);
    System.out.println("Does that work:" + buttonfields[finalI][finalK]);
});

A bit more compact.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top