0

So I'm trying to make the buttons go through each of my tab panels and it works just fine. Now I have to make them repeat the running through the tabs every time one of the tabs reach the end. I made the "previous" button work, and it works, but I can't seem to get the right numeric expression to make the "next" button work. I've tried many different numeric expressions but this is what I have so far:

next = new JButton("next");
    next.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    tabs.setSelectedIndex(tabs.getSelectedIndex()+1);
                    tabs.setSelectedIndex(tabs.getSelectedIndex()-7);
                }
            });

    previous = new JButton("previous");
    previous.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                        tabs.setSelectedIndex(tabs.getSelectedIndex()-1);
                        tabs.setSelectedIndex(tabs.getSelectedIndex()+6);
                }
            });

and this is the Exception that gives me every time I try the next button:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: -6, Tab count: 6

When I finally get it to work, it skips the last tab, so I really don't know what am I doing wrong, but I have a feeling is because of the numeric expression.

4

1 回答 1

3

您应该对边缘情况使用循环。

像这样的东西。

next = new JButton("next");
    next.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    int nextIndex = tabs.getSelectedIndex()+1;
                    tabs.setSelectedIndex( (nextIndex < tabs.getTabCount())?nextIndex:0 );                                                 
                }
            });

    previous = new JButton("previous");
    previous.addActionListener(
            new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    int previousIndex = tabs.getSelectedIndex()-1;
                     tabs.setSelectedIndex((previousIndex < 0)?tabs.getTabCount()-1:previousIndex);                         
                }
            });
于 2013-08-08T02:08:55.570 回答