gpt4 book ai didi

Java 上一个按钮循环

转载 作者:行者123 更新时间:2023-12-01 23:13:58 24 4
gpt4 key购买 nike

除了第一个和最后一个按钮之外,我还尝试创建上一个和下一个按钮。我已经设法让他们全部工作。但是,我似乎无法让上一个和下一个按钮循环遍历数组,而是在到达末尾时出现错误。我什至不知道从哪里开始,但非常感谢所有帮助!

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

最佳答案

previousButtonnextButtonactionPerformed 中,您需要检查当前的 bookIndex 是什么。分别减少或增加。对于 previousButton,如果当前 bookIndex == 0,则将 bookIndex 设置为 inventoryBook.length-1 而不是递减。对于 nextButton,如果 bookIndex == inventoryBook.length-1,则将 bookIndex 设置为 0 而不是递增。因此对于 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);
}
});

关于Java 上一个按钮循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com