我想,以适应经常发生变化,在几个的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