2010-05-25 92 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