I’ve reccently run into issues with indexing my tabs and though I’d give it some concrete ordering by using the setComponentAt method. Here’s my code:
public ContainerPane() {
this.setLayout(new BorderLayout());
myPlayerManagerPane = new PlayerManagerPane();
myGameManagerPane = new GameManagerPane();
myCharacterManagerPane = new CharacterManagerPane();
myPaneTab = new JTabbedPane(JTabbedPane.TOP);
myPaneTab.addTab("Character",myCharacterManagerPane);
myPaneTab.addTab("Player",myPlayerManagerPane);
myPaneTab.addTab("Games",myGameManagerPane);
System.out.println(myPaneTab.getTabCount());
//myPaneTab.setEnabledAt(1, false);
//myPaneTab.setEnabledAt(2, false);
myPaneTab.setComponentAt(0, myPlayerManagerPane);
myPaneTab.setMnemonicAt(0, KeyEvent.VK_1);
myPaneTab.setComponentAt(1, myCharacterManagerPane);
myPaneTab.setMnemonicAt(1, KeyEvent.VK_2);
myPaneTab.setComponentAt(2, myGameManagerPane);<---outOfBoundsException
myPaneTab.setMnemonicAt(2, KeyEvent.VK_3);
add(myPaneTab);
}
So for the count I have, 3 tabs (according to me, and getTabCount()), and I am counting from 0 (correct?). I’m setting the last index the last component that I have. But I still have this printing to screen:
3 <---from tabCount
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
Where am I tripping up, is there an easier way to order my panes?
Edit: Commenting out the setComponent methods, and putting in a for loop I get this output:
There are 3 tabs!
Tab at 0 is Character
Tab at 1 is Player
Tab at 2 is Games
And uncommmenting one pair of methods at a time, I get only 2, of the one I’ve not overwritten, and one of the ones I’ve now set.
Is setComponentAt removing duplicates? Should I ever have fewer than 3 tabs with my set up? Does JTabbedPanel have odd behaviour for duplicate panes?
I’m not sure how or why setComponentAt wasn’t working, though it could be the fact that tabs use a Vector and I’ve heard they are bad.
If you want to have a fixed order of adding, just use
insertTabLike so:Where null is for the icon, and doesn’t accept it as an empty argument.
This way you know in your source code the index of the tab. The only issue with this is that you can’t add a new tab at an index past the current tabCount (which you can find via
getTabCount), i.e. you can’t count 1,3,4 with your tabs!I’m sure you could write a new JTabb Class, and overload the
insertTabmethod to do something more helpful but it might obsfuscate where the tab is (I.e this way you could tell it put the tab at index 2 and it goes into index 1.