Getting indexOutOfBoundsException and I don't know why

12 Views Asked by At

I have been having this problem for a few hours. I don't know what it is, but I am having a hard time thinking clearly at the moment. This method displays a set of images. The first part of the method is just setting the gridbag constraints, whereas the next part in the if statement is creating jlabels and adding them to an arraylist of jlabels. The exception is being thrown when I try and add mouselisteners to the jlabels after they have been added to the arraylist (this is on line 112, and i have commented this on the code).

public void displayComplexStimulus(BufferedImage[] complexStimulus){



    for(int i = 0; i < numberOfElements; i++){
        if (i == 0 || i == 1 || i == 2){
            c.gridx = i;
            c.gridy = 0;
        }
        else if(i == 3 || i == 4 || i == 5){
            c.gridx = i - 3;
            c.gridy = 1;
        }
        else {
            c.gridx = i - 6;
            c.gridy = 2;
        }

        if(counter == 1){



                if (phase1Trial.getPositionOfCorrectImage()!= i){
                    phase1IncorrectLabels.add(new JLabel(new ImageIcon(complexStimulus[i])));
                    phase1IncorrectLabels.get(i).addMouseListener(this);  //line 112
                    add(phase1IncorrectLabels.get(i),c);
                }

                else if(phase1Trial.getPositionOfCorrectImage() == i){
                    correctLabel = new JLabel(new ImageIcon(complexStimulus[i]));
                    add(correctLabel, c);
                    correctLabel.addMouseListener(this);

                }
        }

    }





}
1

There are 1 best solutions below

5
On

If i==phase1Trial.getPositionOfCorrectImage() you're not adding an element to phase1IncorrectLabels. So in the next iteration after adding one element to the array it's at position i-1 and not i. You should replace your get(i) by get(phase1IncorrectLabels.size() - 1).