0
For some reason netbeans asks to transform the variable i
in the end, but if so, I cannot edit it.
Follow the error:
Error: local variable i is accessed from Within Inner class; needs to be declared final
The idea is to create an interface of the old game by adding buttons in a layout with 3 columns and 3 rows.
When it’s time to add eventHandlers
for each button using the FOR cycle, I cannot, as the class method ActionEvent
has the variable be FINAL. What may be wrong?
package TicTacToeProject;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
/**
*
* @author Igor
*/
public class PainelXD extends JPanel {
private final JButton[] botoes;
PainelXD(){
setLayout(new GridLayout(3,3));
botoes = new JButton[9];
for (int i = 0; i <botoes.length; i++) {
botoes[i] = new JButton("btn"+(i+1));
botoes[i].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
botoes[i].setIcon(new ImageIcon(this.getClass().getResource("ticO.png"))); // erro aki local variable i is accessed from within inner class; needs to be declared final
}
});
this.add(botoes[i]);
}
}
}
New code, bug fixed, but now giving ArrayOutOfBounds
sinister and incomprehensible when using the class method ActionListener
on the buttons using click FOR. Why is giving this error?
public class PainelXD extends JPanel {
final JButton[] botoes;
private int lol;
PainelXD(){
setLayout(new GridLayout(3,3));
botoes = new JButton[9];
for (lol = 0; lol <botoes.length; lol++) {
botoes[lol] = new JButton("btn"+(lol+1));
//System.out.println();
botoes[lol].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
botoes[lol].setIcon(new ImageIcon(this.getClass().getResource("ticO.png"))); // erro aki local variable i is accessed from within inner class; needs to be declared final
}
});
this.add(botoes[lol]);
}
}
}
yes, your solution worked. but n understood absolutely nothing of your solution. : DDD
– Igor Augusto
@Igoraugusto I edited with a brief explanation.
– user28595
know q n it’s cool to replicate with a "thank you". but thank you! xd
– Igor Augusto
@Igoraugusto dispose =)
– user28595