2010-05-25 42 views
0

我想,以適應經常發生變化,在幾個的JLabel一個句子中的所有字符。我的3個標籤的寬度始終保持不變。我正在做的是更改字體大小,以便所有字符都可以適應,而不會超出標籤的顯示範圍。我所做的是在句子改變時調用下面的代碼片段。的JLabel不顯示即使動態改變字體大小

這裏是我的代碼

String sentence = "Some long sentence"; 
    int SentenceLength = sentence.length(); 
    int FontSize = 0; 
    // sum of widths of the three labels 
    int TotalLblLength=lbl_0ValueInWords.getWidth()+lbl_1ValueInWords.getWidth()+lbl_1ValueInWords.getWidth(); 

    /*decide the font size so that all the characters can be displayed 
    with out exceeding the display renge(horizontal) of the 3 labels 
    Inconsolata -> monopace font 
    font size == width of the font*2 (something I observed, not sure 
    if this is true always) */ 
    FontSize=(TotalLblLength/SentenceLength)*2;   
    // max font size is 20 - based on label height 
    FontSize=(FontSize>20)?20:FontSize; 

    lbl_0ValueInWords.setFont(new java.awt.Font("Inconsolata", 0,FontSize)); 
    lbl_1ValueInWords.setFont(new java.awt.Font("Inconsolata", 0,FontSize)); 
    lbl_2ValueInWords.setFont(new java.awt.Font("Inconsolata", 0,FontSize)); 

    int CharCount_lbl0 = width_lbl0/(FontSize/2); 
    int CharCount_lbl1 = width_lbl1/(FontSize/2); 
    int CharsCount_lbl2 = width_lbl2/(FontSize/2); 

    /*Set texts of each label 
    if sentence has more than the number of characters that can fit in the 
    1st label, excessive characters are moved to the 2nd label. same goes 
    for the 2nd and 3rd labels*/ 
    if (SentenceLength > CharCount_lbl0) { 
     lbl_0ValueInWords.setText(sentence.substring(0, CharCount_lbl0)); 
     if (SentenceLength > CharCount_lbl0 + CharCount_lbl1) { 
      lbl_1ValueInWords.setText(sentence.substring(CharCount_lbl0, CharCount_lbl0 + CharCount_lbl1)); 
      lbl_2ValueInWords.setText(sentence.substring(CharCount_lbl0 + CharCount_lbl1, SentenceLength)); 
     } else { 
      lbl_1ValueInWords.setText(sentence.substring(CharCount_lbl0, SentenceLength)); 
     } 
    } else { 

     lbl_0ValueInWords.setText(sentence); 
    } 

但即使重新字號有時後的最後一個字符熄滅的顯示範圍。我已經刪除了可能導致此問題的標籤。這發生在隨機長度句子上。我可以通過減少用於計算(希望)標籤寬度

任何人都可以解釋我的原因解決應用程序的問題?可能是因爲字體對稱性的一些缺陷?

回答

2

字體對稱沒有這樣的東西嗎?

有2種類型供您正在處理什麼用的字體。等寬字體和非等寬字體。等寬字體對於每個可以鍵入的單個字符具有相同的確切寬度。其他人不。

最重要的是,字體跨不同操作系統的不同呈現。 Mac上的某些東西在Mac上會長出大約10-20%,因爲它們以不同的方式分隔字體。

不管它是你試圖用的JLabel做,停下來。您不應該使用3個JLabel來顯示3行文本,因爲它們不適合。廢棄它們並使用JTextArea。它具有文字換行,您可以設置字體,並刪除邊距/邊框/填充,並使其不可編輯。您可以非常輕鬆地對其進行自定義,以便與JLabel無法區分,但它會爲您節省大量工作。

爲正確的工作選擇合適的工具。

+0

感謝您的意見 我要說的是,這可能是因爲字體中某些字符的寬度與其他字符的寬度不同 實際上該句子會覆蓋圖像。圖像有三行,我想在這三行顯示句子。所以我覺得我必須經歷同樣的麻煩,才能正確設置文本,即使使用其他jtextcomponent。 我在一些文章中讀到jlabels不適合這種工作(但我選擇使用上述原因的jlabels b'cos)。除了jtextarea提供的額外功能外,是否有任何特別的原因? 謝謝 – Niroshan 2010-05-25 18:42:28