Java上一个按钮循环

时间:2014-02-01 22:27:49

标签: java arrays swing button cycle

我正在尝试创建除了第一个和最后一个按钮之外的上一个和下一个按钮。我设法让他们全部工作。但是,我似乎无法让前一个和下一个按钮在数组中循环,而是在到达结尾时出现错误。我甚至不确定从哪里开始,但非常感谢所有帮助!

    JButton firstButton = new JButton("First");
    buttonPanel.add(firstButton);
    firstButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            bookIndex = 0;
            prepareDisplay(inventoryBook[bookIndex], textArea);
        }
    });

    JButton previousButton = new JButton("Previous");
    buttonPanel.add(previousButton);
    previousButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            bookIndex = bookIndex - 1;
            prepareDisplay(inventoryBook[bookIndex], textArea);
        }
    });

    JButton nextButton = new JButton("Next");
    buttonPanel.add(nextButton);
    nextButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            bookIndex = bookIndex + 1;
            prepareDisplay(inventoryBook[bookIndex], textArea);
        }
    });

    JButton lastButton = new JButton("Last");
    buttonPanel.add(lastButton);
    lastButton.addActionListener(new ActionListener()
    {   
        public void actionPerformed(ActionEvent e)
        {
            bookIndex = (inventoryBook.length - 1);
            prepareDisplay(inventoryBook[bookIndex], textArea);
        }
    });

4 个答案:

答案 0 :(得分:1)

如果下一个按钮的末尾有一个out索引范围,请检查

中的索引
JButton nextButton = new JButton("Next");
    buttonPanel.add(nextButton);
    nextButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            // i guess that here is the problem
            bookIndex = bookIndex + 1;
            prepareDisplay(inventoryBook[bookIndex], textArea);
        }
    });

答案 1 :(得分:1)

actionPerformedpreviousButton的{​​{1}}中,您需要分别在递减或递增之前检查当前nextButton的内容。对于bookIndex,如果是当前previousButton,请将bookIndex设置为bookIndex == 0而不是递减。对于inventoryBook.length-1,如果是nextButton,则将bookIndex == inventoryBook.length-1设置为bookIndex而不是递增。所以0

nextButton

答案 2 :(得分:1)

% Modulo是关键。它将进行所需的循环模拟。

这将使next作为一个循环工作,这意味着当您在最后一个索引处使用next时,它将带您到头。同样适用于prev只需将其更改为bookIndex-1

JButton nextButton = new JButton("Next");
buttonPanel.add(nextButton);
nextButton.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        bookIndex = (bookIndex+1)%inventoryBook.length;
        prepareDisplay(inventoryBook[bookIndex], textArea);
    }
});

答案 3 :(得分:0)

你必须添加一些边界检查,以确保先前不低于0,然后下一步不会超过长度。