Java Iterator | Increase within a sentinel

1
public void actionPerformed(ActionEvent e) {
            i++;
            ImageIcon icon = new ImageIcon(files[i].getAbsolutePath());
            imagem.setIcon(icon);

            frame.add(imagem, BorderLayout.CENTER);  
}
});

I have an array of images, and the goal is to always press the (event) button, iterator i increments its value by one unit and mute the image.

But when I get to the end of the array (when there are no images), it gives me an error and blocks the program. I know I have to do an if (files.lenght) but I'm not sure where to put it. Someone can help me? Thanks

    
asked by anonymous 22.09.2016 / 23:03

1 answer

2

Just make sure the index exists before attempting to access it.

public void actionPerformed(ActionEvent e) {
    i++;

    if(i < files.length()){
        ImageIcon icon = new ImageIcon(files[i].getAbsolutePath());
        imagem.setIcon(icon);    
        frame.add(imagem, BorderLayout.CENTER);  
    } else {
        //fazer alguma coisa
    }
}});

Note: You can not quite understand what you want to do. This will work, but maybe it should not be done like this, if you give more details I can improve the answer.

    
22.09.2016 / 23:11