我想,以適應經常發生變化,在幾個的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);
}
但即使重新字號有時後的最後一個字符熄滅的顯示範圍。我已經刪除了可能導致此問題的標籤。這發生在隨機長度句子上。我可以通過減少用於計算(希望)標籤寬度
任何人都可以解釋我的原因解決應用程序的問題?可能是因爲字體對稱性的一些缺陷?
感謝您的意見 我要說的是,這可能是因爲字體中某些字符的寬度與其他字符的寬度不同 實際上該句子會覆蓋圖像。圖像有三行,我想在這三行顯示句子。所以我覺得我必須經歷同樣的麻煩,才能正確設置文本,即使使用其他jtextcomponent。 我在一些文章中讀到jlabels不適合這種工作(但我選擇使用上述原因的jlabels b'cos)。除了jtextarea提供的額外功能外,是否有任何特別的原因? 謝謝 – Niroshan 2010-05-25 18:42:28