2011-11-15 31 views
3

我有一個很長的文本非常簡單的JLabel。
父佈局是一個GridBagLayout。
我想包含幀的寬度不超過某個值,比如160像素。
所以我將文本設置爲「html」,以便JLabel能夠將文本包裝成多行。
現在我只想「修復」JLabel寬度。但我還沒有找到辦法。
Jframe的最大尺寸,JLabel沒有被佈局管理器檢查,所以我不知道是否有一個「普通」的解決方案。

一個非常簡單的例子(只是修復導入運行)顯示的情況。JLabel進入GridBagLayout。如何修復寬度?

public class SSCE extends JFrame { 

    public static void main(String [] args) { 
     new SSCE().setVisible(true); 
    } 

    public SSCE() { 

     setLayout(new GridBagLayout()); 

     GridBagConstraints gbc = new GridBagConstraints(); 
     gbc.gridx = 0; 
     gbc.gridy = 0; 
     gbc.weightx = 1; 
     gbc.weighty = 1; 
     gbc.fill = GridBagConstraints.BOTH; 

     JLabel label = new JLabel("<html>one two three four five six seven eight nine ten eleven twelve thirteen"); 
     add(label, gbc); 

     gbc.gridy=1; 
     JLabel label2 = new JLabel("other content"); 
     add(label2, gbc); 

     pack(); 

    } 

} 

回答

4

嘗試指定寬度在HTML中,像這樣:

String html = 
    "<html><body width='150px'>" + 
    "Some content that will span 150 pixels and then line-wrap as necessary" + 
    "</body></html>"; 
new JLabel(html); 

請注意,我指定在這個例子中像素(150px),但HTML車身寬度可以指定其他方式。

+1

@AndrewThompson:咦?這只是一些任意數字,關鍵是你可以用這種方式指定寬度。事實上,你是向我展示[在這裏]的人(http://stackoverflow.com/questions/4083322/how-can-i-create-a-jtextarea-with-a-specified-width-and-the -smallest-possible-he/4093402#4093402):) –

+0

@AndrewThompson:Ha:D。我看到你的編輯,我不知道像素是默認的。我敢打賭,相對大小('150%')在這裏不起作用,因爲沒有父HTML組件,對吧? –

+0

*「..對嗎?」*您的JRE與我的一樣好。當你嘗試時發生了什麼? –

2

也許嘗試使用preferedmaximum尺寸爲JLabel

+0

label.setMaximumSize(new Dimension(80,Integer.MAX_VALUE));當然,嘗試。它不起作用。在javadoc中,GridBagLayout據說考慮最大值。也許它在其他情況下評估最大值,例如當它重新分配額外空間時...我不知道。對我來說,瞭解這個佈局管理器的所有細節是相當複雜的。 – AgostinoX

+0

我認爲最大和首選尺寸應該等於您的最大值,在您的情況下是160。 –

2

有一個類似的問題:「做一個JLabel包裹它是通過設置一個最大寬度文本」

而這個答案似乎是正確的:JLabel Max Width Answer