2012-07-31 59 views
3

我已經reccently遇到索引我的選項卡問題,雖然我會給它一些具體的使用setComponentAt方法的順序。這裏是我的代碼:給JTabbedPane訂單

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

所以對我有計,3個標籤(根據我,getTabCount()),而我從0開始計數(正確嗎?)。我將最後一個索引設置爲我擁有的最後一個組件。但我仍然有這種印刷屏幕:

3 <---from tabCount 
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2 

我在哪裏跳了起來,有沒有更容易的方法來訂購我的窗格?

編輯:註釋掉setComponent方法,並把在for循環中,我得到這樣的輸出:

有3個標籤!在0
Tab是性格
選項卡1是玩家
在2 Tab是遊戲

,每次uncommmenting一個對方法,我只得到2,一個我所不被覆蓋,以及我現在設置的其中一個。

setComponentAt刪除重複?我的設置應該少於3個標籤嗎? JTabbedPanel對重複窗格有奇怪的行爲嗎?

回答

0

我不知道如何或爲什麼setComponentAt不工作,但它可能是標籤使用Vector的事實,我聽說他們是壞的。

如果你想有加入一個固定的順序,只需使用insertTab像這樣:

myPaneTab.insertTab("Games",null, myGameManagerPane,"CharacterManagerPane",2); 

其中null是圖標,並且不接受它作爲一個空的參數。

這樣您就可以在源代碼中瞭解該選項卡的索引。唯一的問題是,你不能在當前tabCount(你可以通過getTabCount找到)索引處添加一個新的標籤,也就是說你不能在你的標籤中計數1,3,4!

我敢肯定,你可以寫一個新的JTabb類,並重載insertTab方法做更有用的事情,但它可能會混淆選項卡的位置(即,這樣你可以告訴它把標籤放在索引2,它進入索引1

0

如果你希望你的標籤在另一種秩序,增加他們在其他訂單:

myPaneTab = new JTabbedPane(JTabbedPane.TOP); 
myPaneTab.addTab("Player",myPlayerManagerPane); 
myPaneTab.addTab("Character",myCharacterManagerPane); 
myPaneTab.addTab("Games",myGameManagerPane); 

的Et就萬事大吉了。

+0

這很好,但我有問題不確定標籤索引是什麼我的選項卡......這就是爲什麼我要給*索引。 – Pureferret 2012-07-31 09:43:07

+0

只有當您像上面那樣添加選項卡並在代碼的其餘部分中修改順序時,請問標籤窗格中的索引:'int indexOfGame = tabbedPane.indexOfTabComponent(myGameManagerPane);'。這將允許只在一個地方重新安排標籤。其餘的代碼將保持不變。 – 2012-07-31 09:53:51

2

縱觀setComponentAt的源代碼,你可以看到被刪除你設置該組件:

   int count = getComponentCount(); 
       Component children[] = getComponents(); 
       for (int i = 0; i < count; i++) { 
        if (children[i] == page.component) { 
         super.remove(i); 
        } 
       } 

下一個該組件設置爲頁面的組件(上壓倒一切的最後的禮物組件頁):

page.component = component; 

因此,設置現有選項卡組件的順序,最終會生成2個選項卡。

3

由於您正在嘗試進行的更改而導致出現錯誤 - 將一些窗格自動放入另一個位置刪除另一個選項卡。這就是爲什麼你會得到這個錯誤 - 在一些改變後有少於3個標籤(你可以檢查在每個「setComponentAt」操作之後輸出標籤數量)。

簡單刪除要重新排序,並使用兩種addTabinsertTab的重新進行添加的所有標籤 - 將會把工作沒有任何錯誤完成。