使用 JButton 添加到 ArrayList

Adding to ArrayList with JButton

我目前正在开发 The Game of Life,并且正在尝试在用户按下 gui 中的单元格时使用按钮添加到 ArrayList。

我目前的做法是给我错误:

local variables referenced from an inner class must be final or effectively final

密码是

    private static ArrayList<Integer> coordinates = new ArrayList<Integer>();
    public static void makeCells()
    {
        //Frame Specs
        JFrame frame = new JFrame();
        frame.setVisible(true);
        frame.setSize(1000,1000);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //buttons Panel
        JPanel blocks = new JPanel();
        blocks.setLayout(new GridLayout(50, 50));
        for(int col=0;col<50;col++)
        {
            for(int row = 0; row <50 ;row++)
            {
                JButton button = new JButton();
                blocks.add(button);
                button.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent changeColor)
                        {
                            button.setBackground(Color.YELLOW);
                            final int x = col, y =row;
                            coordinates.add(x);
                            coordinates.add(y);
                        }});
            }
        }
        frame.add(blocks);
    }

如何在不改变方法的情况下解决这个错误?

您可以制作 rowcol 的最终副本:

private static ArrayList<Integer> coordinates = new ArrayList<Integer>();
public static void makeCells()
{
    //Frame Specs
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(1000,1000);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //buttons Panel
    JPanel blocks = new JPanel();
    blocks.setLayout(new GridLayout(50, 50));
    for(int col = 0; col < 50; col++)
    {
        for(int row = 0; row < 50; row++)
        {
            JButton button = new JButton();
            blocks.add(button);
            final int finalRow = row;
            final int finalCol = col;
            button.addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent changeColor)
                    {
                        button.setBackground(Color.YELLOW);
                        int x = finalCol, 
                            y = finalRow;
                        coordinates.add(x);
                        coordinates.add(y);
                    }});
        }
    }
    frame.add(blocks);
}