简体   繁体   English

Java Swing:在actionlistener中设置外部定义的变量

[英]Java Swing: setting variables inside actionlistener that were defined outside

I am new to using swing and I am having trouble with action listeners. 我是使用swing的新手,我在使用动作听众时遇到了麻烦。 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. 如果我在btnGenerate监听器中声明nums和puzzle对象而不将它们作为final,则代码可以工作。 But I want to use the nums array in the btnSolve listener. 但是我想在btnSolve监听器中使用nums数组。

On the lines nums = puzzle.generate(); 在线nums = puzzle.generate(); and nums = puzzle.solve(nums); 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 无法分配最终的局部变量nums,因为它是在封闭类型中定义的

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]; 声明这个final int[][] nums = new int[9][9]; as a class member and not final . 作为集体成员而非final成员。 The message is clear. 消息很清楚。 You cannot modify something that is final . 你不能修改final东西。 You may or may not also need to do the same with Puzzle 您可能也可能不需要对Puzzle进行同样的操作

public class MyClass {

   int[][] nums = new int[9][9];   <-- class member instead of in constructor
   Puzzle puzzle = new Puzzle();

   public MyClass(){
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM