LoginSignup
1
1

More than 3 years have passed since last update.

JLabelの文字が切れる。そんな時...フォントサイズを自動調整する。

Last updated at Posted at 2019-09-01

注意

getFontSizeAdjustedメソッドの -8 しているところはお好みで変えてください。

ソースコード

Example
int fontSizeAdjusted = 0;
int sideMarginSize = 10; // 左右の余白サイズ(片方のみのサイズ)
JLabel label = new JLabel("SampleText");
fontSizeAdjusted = getFontSizeAdjusted(label, label.getText(), sideMarginSize);
label.setFont( new Font(label.getFont().getFamily(), label.getFont().getStyle(). fontSizeAdjusted) );

/**
 * コンポーネントの横幅に収まるフォントサイズを取得する処理
 * @param component コンポーネント
 * @param str 文字列
 * @param sideMarginSize 横の余白サイズ
 * @return fontSize
 */
private int getFontSizeAdjusted(JComponent component, String str, int sideMarginSize) {
    Font font = component.getFont();
    int fontSize = font.getSize();
    int componentWidth = component.getPreferredSize().width - sideMarginSize*2;
    // 「文字列の横の表示サイズ > コンポーネントの横の表示サイズ」である場合、フォントサイズを -1point する。
    while(stringWidth > componentWidth - 8) {
        fontSize--;
        font = new Font(font.getFamily(), font.getStyle(). fontSize);
        stringWidth = component.getFontMetrics(font).stringWidth(str);
    }
    return fontSize;
}

これを書いた理由

検索したら、JLabelに文字を収める方法が全然出てこなかったから。
…JLabelの横のサイズを自動調整する方法はたくさん書いてあった。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1