基本上,这给我一个问题,那就是在添加文本之前,将“ for”循环中的每个按钮声明为最终按钮。当我这样做时,它给了我很多其他错误。有人可以帮我这个忙吗?

import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class tictactoe {
    public static final int FRAME_WIDTH = 700;
    public static final int FRAME_HEIGHT = 200;
    public static void main(String[] args)
    {
        int slots = 9;
        JButton[] gameButton = new JButton[9];

        JPanel ticTacToeBoard = new JPanel();
        ticTacToeBoard.setLayout(new GridLayout(3, 3));
        for (int i = 0; i < slots; i++)
        {

                gameButton[i] = new JButton();
                ticTacToeBoard.add(gameButton[i]);

                gameButton[i].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                gameButton[i].setText("x");
            }
            });
        }



        JButton clearButtons = new JButton("New Game");
        JButton exit = new JButton("Exit");
        JPanel rightPanel = new JPanel();
        JLabel wonLabel = new JLabel();
        rightPanel.setLayout(new GridLayout(1, 3));
        rightPanel.add(wonLabel);
        rightPanel.add(clearButtons);
        rightPanel.add(exit);
        JFrame mainFrame = new JFrame();
        mainFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        mainFrame.setVisible(true);
        mainFrame.setLayout(new GridLayout(1,2));
        mainFrame.add(ticTacToeBoard);
        mainFrame.add(rightPanel);
    }



}

最佳答案

尝试用以下方法替换动作侦听器:

gameButton[i].addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            ((JButton)e.getSource()).setText("x");
}


关于原始错误:

使用任何局部变量,形式化方法参数或异常处理程序参数,但不使用
    在内部类中声明的必须声明为final。任何局部变量,已使用但未使用
    在内部类中声明的声明必须在内部主体之前明确赋值(第16节)
    类。

09-12 18:56