2009-01-24 39 views
1

我試圖獲得一個JTabbedPane,其中所有選項卡(實際選項卡,而不是組件)具有相同的寬度(最寬標籤所需的最小寬度或恆定寬度)。在JTabbedPane中具有相等(恆定)寬度的選項卡

我試過重寫BasicTabbedPaneUI.getTabBounds(int tabIndex, Rectangle dest),但顯然這種方法不被BasicTabbedPaneUI的繪畫方法使用,而是使用rects數組來確定製表符大小。

我的下一個方法是覆蓋JTabbedPane.insertTab(String title, Icon icon, Component component, String tip, int index)並設置標籤組件的首選大小,但這看起來不太優雅,我甚至不確定它是否可以工作。

有沒有辦法做到這一點?

回答

5

答案很簡單。 當我們把選項卡的名稱,使用HTML格式的名稱。 說

TP - JTabbedPane的對象

tp.addTab("<html><body><table width='150'>Name</table></body></html>",Componentobject) 
+0

這聽起來很不錯。我已經看到了其他一些情況,其中html是實現swing的唯一方法(例如,在工具提示上換行)。我一定會試一試。 – Ole 2009-11-07 19:07:58

4

我認爲這並不像你所做的那麼複雜。只需使用setTabComponentAt()和您設置了首選大小的JLabel即可。

+0

這樣的作品,謝謝。不幸的是,我必須自己設置標籤組件的所有其他參數(顏色,字體大小等)。我想通過getTabComponentAt()來檢索標籤,但它始終返回null。 – Ole 2009-01-24 22:35:43

+0

是的,那是因爲getter只能得到一個以前設置的標籤(我認爲doco特別提到了這一點)。 – 2009-01-25 01:48:40

1

我已經試過如下:

tabPane.setUI(new javax.swing.plaf.metal.MetalTabbedPaneUI() { 
    @Override 
    protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) { 
     return super.calculateTabHeight(tabPlacement, tabIndex, fontHeight) + 12; 
    } 
}); 

這似乎爲我工作的罰款。但是如果你使用不同的L,你最終會用「金屬」來渲染它。

我想你可以得到默認的用戶界面,並對其做一個'instanceof'來確定正在使用哪一個,並相應地實例化它。

例如:

TabbedPaneUI ui = tabPane.getUI(); 

if (ui instanceof WindowsTabbedPaneUI) { 
    // Create the windows rendition 
} else if (ui instanceof MetalTabbedPaneUI) { 
    // Create the metal rendition 
} else if (ui instanceof MotifTabbedPaneUI) { 
    // Create the motif rendition 
} else if (ui instanceof SynthTabbedPaneUI) { 
    // Etc... 
} 
0

,這是爲我工作。

JLabel lab = new JLabel(); 
     lab.setPreferredSize(new Dimension(200, 30)); 
     jTabbedPane1.setTabComponentAt(0, lab); // tab index, jLabel 

或嘗試這種變化在相同尺寸的所有標籤成分(稱爲主法)

UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab.contentMargins", new Insets(10, 100, 0, 0));

相關問題