mercredi 15 juin 2016

Referencing integers from a "for loop" within an inner class

Cards are JButtons and I'm trying to add an actionListener to each one as I add them to the world. The cards are in a 2D array and I'm adding them with for loops. However I cannot get a certain card because when I use table[r][c] within the actionListener class, I get an error saying "local variables referenced from an inner class must be final or effectively final". But it's a for loop so I can't make it final. Any help would be appreciated

 for(int r = 0;r<2;r++){
        for(int c=0;c<5;c++){
            int rNum = gen.nextInt(cards.size());

            table[r][c]= new Card("deck",cards.get(rNum), 2);
            cards.remove(rNum);
            add(table[r][c]);
            table[r][c].addActionListener(
                new ActionListener()
                {
                    public void actionPerformed(ActionEvent event){
                        BufferedImage img2 = null;
                        BufferedImage img = null;
                        int pos = table[r][c].getName().indexOf(".");
                        String s = table[r][c].getName().substring(0,pos) + "S" + table[r][c].getName().substring(pos, table[r][c].getName().length());
                        try{
                            img = ImageIO.read(new File(table[r][c].getPat()+"/"+table[r][c].getName()));
                        }catch(IOException e){
                            e.printStackTrace();
                        }
                        try{
                            img2 = ImageIO.read(new File(table[r][c].getPat()+"/"+s));
                        }catch (IOException e){
                            e.printStackTrace();
                        }                
                        if(!table[r][c].isAlive()){
                            ImageIcon imgFace2 = new ImageIcon(img2);
                            table[r][c].setIcon(imgFace2);
                            table[r][c].changeState();
                            number++;
                        }else{
                            ImageIcon imgFace = new ImageIcon(img);
                            table[r][c].setIcon(imgFace);
                            table[r][c].changeState();
                            number--;
                        }           
                    }
                }
            );

Aucun commentaire:

Enregistrer un commentaire