Search code examples
javaarraysswingactionlistenerindexoutofboundsexception

Does anyone know how to add ActionListener to an array of buttons?


I'm creating a project and its similar to mancala. I add ActionListener to an array of buttons with a loop and call the separated handler. At first run I thought it was okay, GUI shows up but when I clicked buttons it was working but the CLI says a lot of errors. On the second running, same code the GUI doesn't show up anymore and CLI says:

Exception in main java lang.ArrayIndexOutOfBoundsException:8

(And other stuff.)

Here's my code:

Handler handler = new Handler();
for( int i = 0; i<=8; i++ )
{btnPods[i].addActionListener( handler ); }

Is this right?


Solution

  • Since java 1.5 (read since long time ago) you can use for-each loop, this will save you from thinking about the array indices:

    
    JButton [] btnPods = ...
    Handler handler = new Handler();
    
    for(JButton btnPod : btnPods) {
        btnPod.addActionListener(handler);
    }