Search code examples
javaswingjlabeljcomboboxindexoutofboundsexception

ArrayIndexOutofBounds/NullPointerException in Java


I am a beginner here in Java. So my problem is I am trying to hide all photo components of my window and make some others appear. But the problem is it always throws Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 10 everytime I select an Item using JComboBox.

Here is the code block for the error:

for (cnt1=0; cnt1<10; cnt1++);
        {
            labels1[cnt1].setVisible(true);
        }

        for (cnt2=0; cnt2<10; cnt2++);
        {
            labels2[cnt2].setVisible(false);
        }


        for (cnt3=0; cnt1<10; cnt3++);
        {
            labels3[cnt3].setVisible(false);
        }

        for (cnt4=0; cnt4<10; cnt4++);
        {
            labels4[cnt4].setVisible(false);
        }

        for (cnt5=0; cnt5<10; cnt5++);
        {
            labels5[cnt5].setVisible(false);
        }

can you tell me what seems to be the problem here. I will post the whole code if you requests for it. Thank you in advance.

Edit: I have fixed the errors in my array, but this time,. the compiler gave me this error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

By the way, this is a snippet of the declaration my arrays:

String iconFiles1[] = {"Articuno.png", "Blastoise.png", "Charizard.png", "Kabutops.png", "Mewtwo.png", "Moltres.png", "Omastar.jpg", "Pikachu.jpg", "Venusaur.png", "Zapdos.png"};
String Jlabels1[] = {"Articuno", "Blastoise", "Charizard", "Kabutops", "Mewtwo", "Moltres", "Omastar", "Pikachu", "Venusaur", "Zapdos"};
ImageIcon icons1[] = new ImageIcon[iconFiles1.length];
JLabel labels1[] = new JLabel[Jlabels1.length];

and this is its assignment in the GUI:

for (int cnt1=0; cnt1<labels1.length; cnt1++)
        {
            labels1[cnt1].setVisible(true);
        }

am I doing it right? Answers are appreciated. Again. Thank you.


Solution

  • You appear to have incorrect variables in at least one of your for loops (as several other posters have already pointed out).

    Nonetheless, the reason you're getting an ArrayIndexOutOfBoundsException is because you have semicolons after all of your for loops, thereby making them do nothing but increment your counter variables. The variables that you're incrementing in your for loops are not locally declared in the for loops themselves, so their scope is whatever function you're currently in (aka they exist outside of the for loops). So when the loops finish incrementing, your counters will be too large (10 in this case)---> hence the ArrayIndexOutOfBoundsException: 10.