I am new to using swing and I am having trouble with action listeners. I have an action listener set up for when a button is pressed and I am getting an error message when I try to set the value of a variable defined outside the listener. Here is the code
// create puzzle object and array for puzzle numbers
final Puzzle puzzle = new Puzzle();
final int[][] nums = new int[9][9];
// create buttons
JButton btnSolve = new JButton("Solve");
btnSolve.setEnabled(false);
JButton btnGenerate = new JButton("Generate");
// When generate button is clicked
btnGenerate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// generate puzzle
nums = puzzle.generate();
// fill board with puzzle
fillBoard(nums);
// enable solve button
btnSolve.setEnabled(true);
}
});
// When solve button is clicked
btnSolve.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// solve the puzzle
nums = puzzle.solve(nums);
// fill board with solved puzzle
fillBoard(nums);
}
});
The code works if I declare the nums and puzzle objects inside the btnGenerate listener without them being final. But I want to use the nums array in the btnSolve listener.
On the lines nums = puzzle.generate();
and nums = puzzle.solve(nums);
I am getting the error:
The final local variable nums cannot be assigned, since it is defined in an enclosing type
What does it mean by "defined in an enclosing type" and how should this be done?
Thanks in advance.
Declare this final int[][] nums = new int[9][9];
as a class member and not final
. The message is clear. You cannot modify something that is final
. You may or may not also need to do the same with Puzzle
public class MyClass {
int[][] nums = new int[9][9]; <-- class member instead of in constructor
Puzzle puzzle = new Puzzle();
public MyClass(){
}
}
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.