2016-10-28 9 views
0

私は現在The Game of Lifeに取り組んでおり、ユーザがguiのセルを押したときにボタンでArrayListを追加しようとしています。JButtonで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); 
    } 

です:

私の現在のアプローチは私にエラーを与えていますか?

+0

を、エラーメッセージをGoogleにしてください。 –

答えて

1

あなたが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); 
} 
関連する問題