Java 数组列表导航 [英] Java arraylist navigation

查看:27
本文介绍了Java 数组列表导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我更正我的 if 语句.我正在尝试浏览 arraylist 元素,但在某些情况下,下一个和上一个按钮显示命令行错误.错误各不相同,但它们有以下共同点...

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....

这是代码

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;
        }
    }
}}

推荐答案

您收到该异常是因为您正在递增/递减计数器、访问 ArrayList,然后进行检查.

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

您需要做的是递增/递减计数器,进行检查,然后访问 ArrayList.

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

ArrayLists 有基于 0 的位置,因此您需要确保可能的最小位置为 0,并且可能的最大位置比 ArrayList 中的项目数量少 1.

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.

你需要做的是这样的:

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

在你的第二部分

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();

在你的第二部分

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

这篇关于Java 数组列表导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆