Search code examples
javaarraysswingbuttoncycle

Java previous button cycle


I am trying to create previous and next buttons in addition to my first and last buttons. I have managed to get them all to work. However, I cannot seem to get the previous and next buttons to cycle through the array and instead I get errors when reaching the end. I'm not even sure where to start, but all help is very much appreciated!

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

Solution

  • In the actionPerformed for the previousButton and nextButton you need to check what the current bookIndex is before you decrement or increment, respectively. In the case of previousButton, if the current bookIndex == 0, set the bookIndex to inventoryBook.length-1 instead of decrementing. For the nextButton, if the bookIndex == inventoryBook.length-1, set bookIndex to 0 instead of incrementing. So for nextButton:

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