I'm writing a simple program, and there is one problem I cannot solve.
I am creating textFields with such loop:
testText = new JTextField[9][9];
for(int x = 0; x < 9; x++)
for(int y = 0; y < 9; y++)
{
testText[x][y] = new JTextField();
testText[x][y].setPreferredSize(new Dimension(30, 30));
testText[x][y].setHorizontalAlignment(SwingConstants.CENTER);
testText[x][y].setFont(new Font("Tahoma", Font.BOLD, 18));
testText[x][y].setBackground(Color.WHITE);
testText[x][y].setEditable(false);
testText[x][y].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if( //blablabla )
testText[x][y].setText(value + "");
}
});
panelMain.add(testText[x][y]);
}
I want to use the x, and y to get the location of this "clicked" field, but the mysterious error apperas: "Local variable x defined in an enclosing scope must be final or effectively final" (same for "y")
In my project there would be checking function and it would be great if I could use those x and y as arguments like :
checkIfPossibel(x,y,value); // "value" is global
Keep in mind that I am not a Java God and I would like to keep this work on understandable level(for me) if this is possible.
The best fix here is to simplify your code - remove all that duplication of testTest[x][y]
by introducing a local variable which can be final (and thus allow you to use it within the anonymous inner class):
testText = new JTextField[9][9];
for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++)
{
final JTextField field = new JTextField();
testText[x][y] = field;
field.setPreferredSize(new Dimension(30, 30));
field.setHorizontalAlignment(SwingConstants.CENTER);
field.setFont(new Font("Tahoma", Font.BOLD, 18));
field.setBackground(Color.WHITE);
field.setEditable(false);
field.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (//blablabla) {
field.setText(value + "");
}
}
});
panelMain.add(field);
}
}
It's not clear whether you even need testText
at this point, but I'll assume for the moment that you are referring to it somewhere else.
See more on this question at Stackoverflow