添加操作与数组一起执行

问题描述

我正在编写井字游戏。

我通过数组创建了按钮,但是现在我尝试通过for循环向每个Button添加一个ActionListener和一个actionPerformed。当我尝试这样做时,会发生错误:

在封闭范围内定义的局部变量i必须是最终的或实际上是最终的

我不知道该如何解决。 (在第35行: System.out.println("You clicked the Button" + i + "," + k);

import java.awt.FlowLayout;
import java.util.Random;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToearray {
    
    static String players; 
    static JLabel gametext;
    static int round;
    static int maxWidth = 3;
    static int maxHeight = 3;
    static JButton[][] buttonfields = new JButton[maxWidth][maxHeight];
    
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        JFrame mainFrame = new JFrame("Tic-Tac-Toe");
        mainFrame.getContentPane().setLayout(new FlowLayout());
        for (int i = 0; i < maxWidth; i++) {
            for (int k = 0; k < maxHeight; k++) {
                buttonfields [i][k] = new JButton("  ");
                mainFrame.add(buttonfields[i][k],maxWidth * i + k);
                buttonfields[i][k].addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("You clicked the Button" + i + "," + k);
                        System.out.println("Does that work:" + buttonfields[i][k]);
                    }
                });
            }
        }
        mainFrame.pack();
        mainFrame.setVisible(true);
        mainFrame.setResizable(true);
        mainFrame.setSize(180,150);
        mainFrame.setResizable(false);
        JLabel gametext = new JLabel();
        mainFrame.add(gametext);
        mainFrame.setLocationRelativeTo(null);
        Random rand = new Random();
        int beginnernr = rand.nextInt(2);
        if (beginnernr == 1) {
            players = "O";
            gametext.setText("It's " + players + " turn!");
        } if (beginnernr == 0) {
            players = "X";
            gametext.setText("It's " + players + " turn!");
        }
        if (round == 9) {
            gametext.setText("Game Over");
        }
    }
}

解决方法

您尝试创建的'Anonymous'new ActionListener() {...}(可以用lambda 代替)是在按钮上的操作完成后将执行的操作。为了能够编译在匿名/ lambda中使用的值,它们必须是最终值,以确保它们可以在运行时访问。

快速修复可以是这样的:

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]);
    }
});

此外,使用lambdas的代码如下所示:

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]);
});

更紧凑。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...