0

I am currently working on The Game of Life, and am trying to add to an ArrayList with a button when a user presses the cell in the gui.

My current approach is giving me the error:

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

the code is

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

How can I resolve this error without changing my approach?

1
  • In the future, please Google the error message as this question is asked at least several times per week. Commented Oct 28, 2016 at 23:29

1 Answer 1

1

You can make final copies of row and col:

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.