2

基本上,它给我一个关于在添加文本之前将“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);
    }



}
4

2 回答 2

5

尝试用这个替换动作监听器:

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

关于原来的错误:

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

于 2012-07-15T23:52:18.153 回答
0

只需添加:

String buttonText = "Click Me";
jButton.setText(buttonText);
于 2013-06-18T19:09:43.103 回答