user1106130
user1106130

Reputation: 301

Java arraylist navigation

Please help me correct my if statements. I am trying to navigate through the arraylist elements but in some cases next and previous button displays command line errors. the errors vary but they have in common the following...

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index....

heres the code

public class buttonListener implements ActionListener {
    public void actionPerformed(ActionEvent x){
        if (x.getSource() == nxtButton){
            indexCounter++;
            balanceFrame.setVisible(false);
            callDetail();

            if(indexCounter == filePaths.size()-1) { //max counter...we dont want to exceed the max number, size of array
                indexCounter = -1;
        }
    }
    else if (x.getSource() == prevButton){
        indexCounter--;
        balanceFrame.setVisible(false);
        callDetail();
        if(indexCounter == 0){
            indexCounter = filePaths.size()-1;
        }
    }
}}

Upvotes: 0

Views: 1668

Answers (2)

npinti
npinti

Reputation: 52185

You are getting that exception because you are incrementing/decrementing the counter, access the ArrayList, and then, make the check.

What you need to do is to increment/decrement the counter, make the check, and then access the ArrayList.

ArrayLists are have 0 based locations, so you need to make sure that the smallest location possible is 0 and that the maximum location possible is one less than the amount of items in the ArrayList.

What you need to do is something like this:

indexCounter++;
if (indexCounter > (filePaths.size - 1))
{
    indexCounter = filePaths.size - 1;
}
callDetail();

and in your second part

indexCounter--;
if (indexCounter < 0)
{
    indexCounter = 0;
}
callDetail();

This will cause the user to keep viewing the last record if he/she keeps pressing next and the first record if he/she keeps pressing previous.

On second note, you seem to want to implement a Circular list, so this should work:

indexCounter++;
if (indexCounter > (filePaths.size - 1))
{
    indexCounter = 0;
}
callDetail();

and in your second part

indexCounter--;
if (indexCounter < 0)
{
    indexCounter = filePaths.size - 1;
}
callDetail();

Upvotes: 2

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47913

Your question is a little bit vague, but I think the problem is here:

indexCounter = -1;

I think what you actually wanted is:

indexCounter -= 1; // indexCounter = indexCounter - 1

Your if condition seems to wrong as well. It should be like this:

if (indexCounter == filePaths.size()) {
    indexCounter -= 1; // indexCounter = indexCounter - 1
}

Or even better:

if (indexCounter >= filePaths.size()) {
    indexCounter = filePaths.size() - 1;
}

Also, on a side note, in Java the convention is to use CamelCase for class names. So your class should be named ButtonListener and not buttonListener.

Upvotes: 1

Related Questions