0

頻繁に変わる文をいくつかのjlabelsに収めようとしています。私の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);
    }

ただし、フォントサイズをリセットした後でも、最後の文字が表示範囲外になることがあります。これを引き起こす可能性のあるjlabelsからマージンを削除しました。これは、ランダムな長さの文で発生します。計算に使用するラベル幅を小さくすることで、アプリケーションの問題を解決できます(うまくいけば)

誰かが私に理由を説明できますか?フォントの対称性に何らかの欠陥があるためでしょうか?

4

1 に答える 1

2

フォントの対称性などはありませんか?

扱っているものには2種類のフォントがあります。等幅フォントと非等幅フォント。等幅フォントは、入力できるすべての文字の幅が正確に同じです。他の人はしません。

その上、フォントは OS ごとに異なる方法でレンダリングされます。Windows ではフォントの間隔が異なるため、Mac では約 10 ~ 20% 長くなります。

JLabels で何をしようとしても、やめてください。収まらないため、3 行のテキストを表示するために 3 つの JLabel を使用しないでください。それらをスクラップして、JTextArea を使用します。テキストの折り返しがあり、フォントを設定し、マージン/ボーダー/パディングを削除して編集不可にすることができます。非常に簡単にカスタマイズできるため、JLabel と見分けがつきませんが、大量の作業を節約できます。

適切なジョブに適切なツールを選択してください。

于 2010-05-25T17:36:42.090 に答える