0

我正在尝试将一个经常变化的句子放入几个 jlabels 中。我的 3 个 jlabels 的宽度一直保持不变。我正在做的是更改字体大小,以便所有字符都可以适应而不会超出标签的显示范围。我所做的是在更改句子时调用下面的代码片段。

这是我的代码

    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);
    }

但即使在重置字体大小后,有时最后一个字符也会超出显示范围。我已经从可能导致这种情况的 jlabels 中删除了边距。这发生在随机长度的句子上。我可以通过减少用于计算的标签宽度来解决应用程序的问题(希望如此)

谁能解释一下原因?可能是因为字体对称性的一些缺陷?

4

1 回答 1

2

没有字体对称之类的东西吗?

您正在处理的字体有 2 种类型。等宽字体和非等宽字体。对于您可以键入的每个字符,等宽字体具有相同的确切宽度。其他人没有。

最重要的是,字体在不同操作系统中的呈现方式不同。Windows 上的某些东西在 Mac 上会长约 10-20%,因为它们以不同的方式分隔字体。

无论您想用 JLabels 做什么,都停下来。您不应该使用 3 个 JLabel 来显示 3 行文本,因为它们不适合。报废它们并使用 JTextArea。它具有文本换行,您可以设置字体,并删除边距/边框/填充并使其不可编辑。您可以非常轻松地对其进行自定义,使其与 JLabel 没有区别,但它会为您节省大量工作。

为正确的工作选择正确的工具。

于 2010-05-25T17:36:42.090 回答